{"id": 38231, "name": "Bitwise operations", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n"}
{"id": 38232, "name": "Dragon curve", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n"}
{"id": 38233, "name": "Read a file line by line", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n"}
{"id": 38234, "name": "Doubly-linked list_Element insertion", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n"}
{"id": 38235, "name": "Smarandache prime-digital sequence", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n"}
{"id": 38236, "name": "Quickselect algorithm", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 38237, "name": "Non-decimal radices_Convert", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n"}
{"id": 38238, "name": "Walk a directory_Recursively", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n"}
{"id": 38239, "name": "Main step of GOST 28147-89", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n", "C++": "UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)\n{\n    UINT_64 N;\n\tN = N1;\n\tN = (N<<32)|N2;\n\treturn UINT_64(N);\n}\n\nUINT_32 TGost::ReplaceBlock(UINT_32 x)\n{   \n    register i;\n    UINT_32 res = 0UL;\n    for(i=7;i>=0;i--)\n    {\n       ui4_0 = x>>(i*4);\n       ui4_0 = BS[ui4_0][i];\n       res = (res<<4)|ui4_0;\n    }\n    return res;\n}\n\nUINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)\n{\n   UINT_32 N1,N2,S=0UL;\n   N1=UINT_32(N);\n   N2=N>>32;\n   S = N1 + X % 0x4000000000000;\n   S = ReplaceBlock(S);\n   S = (S<<11)|(S>>21);\n   S ^= N2;\n   N2 = N1;\n   N1 = S;\n   return SWAP32(N2,N1);\n}\n"}
{"id": 38240, "name": "State name puzzle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n"}
{"id": 38241, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n"}
{"id": 38242, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 38243, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 38244, "name": "Classes", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n"}
{"id": 38245, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38246, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38247, "name": "LZW compression", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n"}
{"id": 38248, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 38249, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 38250, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 38251, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 38252, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 38253, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 38254, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 38255, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 38256, "name": "Mertens function", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n"}
{"id": 38257, "name": "Order by pair comparisons", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n"}
{"id": 38258, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 38259, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 38260, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 38261, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 38262, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n"}
{"id": 38263, "name": "Snake", "C": "\n\n\n\n\n\n\n\n\nchar nonblocking_getch();\nvoid positional_putch(int x, int y, char ch);\nvoid millisecond_sleep(int n);\nvoid init_screen();\nvoid update_screen();\nvoid close_screen();\n\n\n\n#ifdef __linux__\n#define _POSIX_C_SOURCE 200809L\n#include <time.h> \n#include <ncurses.h> \nchar nonblocking_getch() { return getch(); }\nvoid positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }\nvoid millisecond_sleep(int n) { \n\tstruct timespec t = { 0, n * 1000000 };\n\tnanosleep(&t, 0);\n\t\n}\nvoid update_screen() { refresh(); }\nvoid init_screen() {\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\tnodelay(stdscr, TRUE);\n}\nvoid close_screen() { endwin(); }\n#endif\n\n\n#ifdef _WIN32\n#error \"not implemented\"\n#endif\n\n\n#include <time.h> \n#include <stdlib.h> \n\n#define w 80\n#define h 40\n\nint board[w * h];\nint head;\nenum Dir { N, E, S, W } dir;\nint quit;\n\nenum State { SPACE=0, FOOD=1, BORDER=2 };\n\n\n\nvoid age() {\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tif(board[i] < 0)\n\t\t\t++board[i];\n}\n\n\nvoid plant() {\n\tint r;\n\tdo\n\t\tr = rand() % (w * h);\n\twhile(board[r] != SPACE);\n\tboard[r] = FOOD;\n}\n\n\nvoid start(void) {\n        int i;\n\tfor(i = 0; i < w; ++i)\n\t\tboard[i] = board[i + (h - 1) * w] = BORDER;\n\tfor(i = 0; i < h; ++i)\n\t\tboard[i * w] = board[i * w + w - 1] = BORDER;\n\thead = w * (h - 1 - h % 2) / 2; \n\tboard[head] = -5;\n\tdir = N;\n\tquit = 0;\n\tsrand(time(0));\n\tplant();\n}\n\nvoid step() {\n\tint len = board[head];\n\tswitch(dir) {\n\t\tcase N: head -= w; break;\n\t\tcase S: head += w; break;\n\t\tcase W: --head; break;\n\t\tcase E: ++head; break;\n\t}\n\tswitch(board[head]) {\n\t\tcase SPACE:\n\t\t\tboard[head] = len - 1; \n\t\t\tage();\n\t\t\tbreak;\n\t\tcase FOOD:\n\t\t\tboard[head] = len - 1;\n\t\t\tplant();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tquit = 1;\n\t}\n}\n\nvoid show() {\n\tconst char * symbol = \" @.\";\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tpositional_putch(i / w, i % w,\n\t\t\tboard[i] < 0 ? '#' : symbol[board[i]]);\n\tupdate_screen();\n}\n\nint main (int argc, char * argv[]) {\n\tinit_screen();\n\tstart();\n\tdo {\n\t\tshow();\n\t\tswitch(nonblocking_getch()) {\n\t\t\tcase 'i': dir = N; break;\n\t\t\tcase 'j': dir = W; break;\n\t\t\tcase 'k': dir = S; break;\n\t\t\tcase 'l': dir = E; break;\n\t\t\tcase 'q': quit = 1; break;\n\t\t}\n\t\tstep();\n\t\tmillisecond_sleep(100); \n\t\t\n\t}\n\twhile(!quit);\n\tmillisecond_sleep(999);\n\tclose_screen();\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nconst int WID = 60, HEI = 30, MAX_LEN = 600;\nenum DIR { NORTH, EAST, SOUTH, WEST };\n\nclass snake {\npublic:\n    snake() {\n        console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( \"Snake\" ); \n        COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );\n        SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );\n        CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );\n    }\n    void play() {\n        std::string a;\n        while( 1 ) {\n            createField(); alive = true;\n            while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }\n            COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );\n            SetConsoleTextAttribute( console, 0x000b );\n            std::cout << \"Play again [Y/N]? \"; std::cin >> a;\n            if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;\n        }\n    }\nprivate:\n    void createField() {\n        COORD coord = { 0, 0 }; DWORD c;\n        FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );\n        FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );\n        SetConsoleCursorPosition( console, coord );\n        int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;\n        for( x = 0; x < WID; x++ ) {\n            brd[x] = brd[x + WID * ( HEI - 1 )] = '+';\n        }\n        for( ; y < HEI; y++ ) {\n            brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';\n        }\n        do {\n            x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n        } while( brd[x + WID * y] );\n        brd[x + WID * y] = '@';\n        tailIdx = 0; headIdx = 4; x = 3; y = 2;\n        for( int c = tailIdx; c < headIdx; c++ ) {\n            brd[x + WID * y] = '#';\n            snk[c].X = 3 + c; snk[c].Y = 2;\n        }\n        head = snk[3]; dir = EAST; points = 0;\n    }\n    void readKey() {\n        if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;\n        if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;\n        if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;\n        if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;\n    }\n    void drawField() {\n        COORD coord; char t;\n        for( int y = 0; y < HEI; y++ ) {\n            coord.Y = y;\n            for( int x = 0; x < WID; x++ ) {\n                t = brd[x + WID * y]; if( !t ) continue;\n                coord.X = x; SetConsoleCursorPosition( console, coord );\n                if( coord.X == head.X && coord.Y == head.Y ) {\n                    SetConsoleTextAttribute( console, 0x002e );\n                    std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );\n                    continue;\n                }\n                switch( t ) {\n                    case '#': SetConsoleTextAttribute( console, 0x002a ); break;\n                    case '+': SetConsoleTextAttribute( console, 0x0019 ); break;\n                    case '@': SetConsoleTextAttribute( console, 0x004c ); break;\n                }\n                std::cout << t; SetConsoleTextAttribute( console, 0x0000 );\n            }\n        }\n        std::cout << t; SetConsoleTextAttribute( console, 0x0007 );\n        COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );\n        std::cout << \"Points: \" << points;\n    }\n    void moveSnake() {\n        switch( dir ) {\n            case NORTH: head.Y--; break;\n            case EAST: head.X++; break;\n            case SOUTH: head.Y++; break;\n            case WEST: head.X--; break;\n        }\n        char t = brd[head.X + WID * head.Y];\n        if( t && t != '@' ) { alive = false; return; }\n        brd[head.X + WID * head.Y] = '#';\n        snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;\n        if( ++headIdx >= MAX_LEN ) headIdx = 0;\n        if( t == '@' ) {\n            points++; int x, y;\n            do {\n                x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n            } while( brd[x + WID * y] );\n            brd[x + WID * y] = '@'; return;\n        }\n        SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';\n        brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;\n        if( ++tailIdx >= MAX_LEN ) tailIdx = 0;\n    }\n    bool alive; char brd[WID * HEI]; \n    HANDLE console; DIR dir; COORD snk[MAX_LEN];\n    COORD head; int tailIdx, headIdx, points;\n};\nint main( int argc, char* argv[] ) {\n    srand( static_cast<unsigned>( time( NULL ) ) );\n    snake s; s.play(); return 0;\n}\n"}
{"id": 38264, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38265, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38266, "name": "Legendre prime counting function", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n"}
{"id": 38267, "name": "Use another language to call a function", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n"}
{"id": 38268, "name": "Longest string challenge", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n"}
{"id": 38269, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 38270, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 38271, "name": "Create a file", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 38272, "name": "Unprimeable numbers", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n"}
{"id": 38273, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 38274, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 38275, "name": "Chernick's Carmichael numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 38276, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 38277, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 38278, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 38279, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 38280, "name": "Create an object at a given address", "C": "#include <stdio.h>\n\nint main()\n{\n  int intspace;\n  int *address;\n\n  address = &intspace; \n  *address = 65535;\n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  \n  *((char*)address) = 0x00;\n  *((char*)address+1) = 0x00;\n  *((char*)address+2) = 0xff;\n  *((char*)address+3) = 0xff; \n  \n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  return 0;\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main()\n{\n    \n    char* data = new char[sizeof(std::string)];\n\n    \n    std::string* stringPtr = new (data) std::string(\"ABCD\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    \n    stringPtr->~basic_string();\n    stringPtr = new (data) std::string(\"123456\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    stringPtr->~basic_string();\n    delete[] data;\n}\n"}
{"id": 38281, "name": "Sequence of primorial primes", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 38282, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 38283, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 38284, "name": "Dining philosophers", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n"}
{"id": 38285, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 38286, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 38287, "name": "Logistic curve fitting in epidemiology", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n"}
{"id": 38288, "name": "Sorting algorithms_Strand sort", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n"}
{"id": 38289, "name": "Additive primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n"}
{"id": 38290, "name": "Inverted syntax", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n"}
{"id": 38291, "name": "Inverted syntax", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n"}
{"id": 38292, "name": "Inverted syntax", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n"}
{"id": 38293, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 38294, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 38295, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 38296, "name": "Delegates", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n"}
{"id": 38297, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 38298, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 38299, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 38300, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 38301, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 38302, "name": "Enforced immutability", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n"}
{"id": 38303, "name": "Sutherland-Hodgman polygon clipping", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38304, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 38305, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 38306, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n"}
{"id": 38307, "name": "Optional parameters", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n"}
{"id": 38308, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 38309, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 38310, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 38311, "name": "Call a foreign-language function", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n"}
{"id": 38312, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 38313, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 38314, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 38315, "name": "Faulhaber's triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n"}
{"id": 38316, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 38317, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 38318, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 38319, "name": "Word wheel", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38320, "name": "Array concatenation", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"}
{"id": 38321, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 38322, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 38323, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 38324, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 38325, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 38326, "name": "Primes - allocate descendants to their ancestors", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n"}
{"id": 38327, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 38328, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 38329, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 38330, "name": "First-class functions", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n"}
{"id": 38331, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n"}
{"id": 38332, "name": "XML_Output", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 38333, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 38334, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 38335, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 38336, "name": "Regular expressions", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n"}
{"id": 38337, "name": "Guess the number_With feedback (player)", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n"}
{"id": 38338, "name": "Hash from two arrays", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n"}
{"id": 38339, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 38340, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 38341, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 38342, "name": "Fractal tree", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n"}
{"id": 38343, "name": "Colour pinstripe_Display", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n"}
{"id": 38344, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 38345, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 38346, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n"}
{"id": 38347, "name": "Animate a pendulum", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n"}
{"id": 38348, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 38349, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 38350, "name": "Create a file on magnetic tape", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n"}
{"id": 38351, "name": "Sorting algorithms_Heapsort", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 38352, "name": "Playing cards", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 38353, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 38354, "name": "Sierpinski carpet", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n"}
{"id": 38355, "name": "Sorting algorithms_Bogosort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 38356, "name": "Merge and aggregate datasets", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n"}
{"id": 38357, "name": "Euler method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n"}
{"id": 38358, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 38359, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 38360, "name": "JortSort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n"}
{"id": 38361, "name": "Leap year", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n"}
{"id": 38362, "name": "Combinations and permutations", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n"}
{"id": 38363, "name": "Sort numbers lexicographically", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n"}
{"id": 38364, "name": "Number names", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n"}
{"id": 38365, "name": "Compare length of two strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38366, "name": "Sorting algorithms_Shell sort", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n"}
{"id": 38367, "name": "Doubly-linked list_Definition", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n"}
{"id": 38368, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n"}
{"id": 38369, "name": "Permutation test", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n"}
{"id": 38370, "name": "Möbius function", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 38371, "name": "Increment a numerical string", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n"}
{"id": 38372, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 38373, "name": "Sorting algorithms_Permutation sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n"}
{"id": 38374, "name": "Averages_Arithmetic mean", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n"}
{"id": 38375, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 38376, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 38377, "name": "Entropy", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n"}
{"id": 38378, "name": "Tokenize a string with escaping", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n"}
{"id": 38379, "name": "Hello world_Text", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n"}
{"id": 38380, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n"}
{"id": 38381, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n"}
{"id": 38382, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n"}
{"id": 38383, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n"}
{"id": 38384, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 38385, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n"}
{"id": 38386, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 38387, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 38388, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n"}
{"id": 38389, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 38390, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 38391, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 38392, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n"}
{"id": 38393, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n"}
{"id": 38394, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n"}
{"id": 38395, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n"}
{"id": 38396, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 38397, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 38398, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n"}
{"id": 38399, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n"}
{"id": 38400, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n"}
{"id": 38401, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 38402, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 38403, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 38404, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 38405, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n"}
{"id": 38406, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38407, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 38408, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n"}
{"id": 38409, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 38410, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n"}
{"id": 38411, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n"}
{"id": 38412, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n"}
{"id": 38413, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 38414, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 38415, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n"}
{"id": 38416, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 38417, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 38418, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n"}
{"id": 38419, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 38420, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38421, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n"}
{"id": 38422, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n"}
{"id": 38423, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38424, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 38425, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 38426, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n"}
{"id": 38427, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 38428, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n"}
{"id": 38429, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 38430, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 38431, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n"}
{"id": 38432, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n"}
{"id": 38433, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n"}
{"id": 38434, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n"}
{"id": 38435, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n"}
{"id": 38436, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n"}
{"id": 38437, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38438, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38439, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n"}
{"id": 38440, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n"}
{"id": 38441, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38442, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 38443, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n"}
{"id": 38444, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 38445, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n"}
{"id": 38446, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n"}
{"id": 38447, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 38448, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 38449, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n"}
{"id": 38450, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38451, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n"}
{"id": 38452, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 38453, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 38454, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 38455, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 38456, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"}
{"id": 38457, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 38458, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 38459, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n"}
{"id": 38460, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n"}
{"id": 38461, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n"}
{"id": 38462, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n"}
{"id": 38463, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n"}
{"id": 38464, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 38465, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 38466, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 38467, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 38468, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n"}
{"id": 38469, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 38470, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 38471, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 38472, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n"}
{"id": 38473, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n"}
{"id": 38474, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 38475, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n"}
{"id": 38476, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n"}
{"id": 38477, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n"}
{"id": 38478, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 38479, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n"}
{"id": 38480, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n"}
{"id": 38481, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n"}
{"id": 38482, "name": "Hello world_Text", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n"}
{"id": 38483, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 38484, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 38485, "name": "Dragon curve", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n"}
{"id": 38486, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 38487, "name": "Doubly-linked list_Element insertion", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n"}
{"id": 38488, "name": "Smarandache prime-digital sequence", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n"}
{"id": 38489, "name": "Smarandache prime-digital sequence", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n"}
{"id": 38490, "name": "Quickselect algorithm", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n"}
{"id": 38491, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "Python": "i = int('1a',16)  \n"}
{"id": 38492, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 38493, "name": "State name puzzle", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n"}
{"id": 38494, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 38495, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 38496, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 38497, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 38498, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 38499, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 38500, "name": "LZW compression", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 38501, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 38502, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 38503, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 38504, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 38505, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 38506, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 38507, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 38508, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 38509, "name": "Mertens function", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n"}
{"id": 38510, "name": "Order by pair comparisons", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n"}
{"id": 38511, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 38512, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 38513, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 38514, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 38515, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 38516, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 38517, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 38518, "name": "Legendre prime counting function", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n"}
{"id": 38519, "name": "Use another language to call a function", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n"}
{"id": 38520, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 38521, "name": "Universal Turing machine", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 38522, "name": "Universal Turing machine", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 38523, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 38524, "name": "Unprimeable numbers", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n"}
{"id": 38525, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 38526, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 38527, "name": "Chernick's Carmichael numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n"}
{"id": 38528, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 38529, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 38530, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 38531, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 38532, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 38533, "name": "Sequence of primorial primes", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n"}
{"id": 38534, "name": "Sequence of primorial primes", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n"}
{"id": 38535, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 38536, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 38537, "name": "Dining philosophers", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n"}
{"id": 38538, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 38539, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 38540, "name": "Logistic curve fitting in epidemiology", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n"}
{"id": 38541, "name": "Sorting algorithms_Strand sort", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n"}
{"id": 38542, "name": "Additive primes", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 38543, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 38544, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 38545, "name": "Delegates", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 38546, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 38547, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 38548, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 38549, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 38550, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 38551, "name": "Enforced immutability", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 38552, "name": "Sutherland-Hodgman polygon clipping", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n"}
{"id": 38553, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 38554, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 38555, "name": "Spiral matrix", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n"}
{"id": 38556, "name": "Optional parameters", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n"}
{"id": 38557, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 38558, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 38559, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 38560, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 38561, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 38562, "name": "Faulhaber's triangle", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 38563, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 38564, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 38565, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 38566, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 38567, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 38568, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 38569, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 38570, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 38571, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 38572, "name": "Primes - allocate descendants to their ancestors", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n"}
{"id": 38573, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 38574, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 38575, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 38576, "name": "First-class functions", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 38577, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 38578, "name": "XML_Output", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n"}
{"id": 38579, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 38580, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 38581, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 38582, "name": "Guess the number_With feedback (player)", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n"}
{"id": 38583, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 38584, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 38585, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 38586, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 38587, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 38588, "name": "Fractal tree", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n"}
{"id": 38589, "name": "Colour pinstripe_Display", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n"}
{"id": 38590, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 38591, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 38592, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 38593, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n"}
{"id": 38594, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n"}
{"id": 38595, "name": "Animate a pendulum", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n"}
{"id": 38596, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 38597, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 38598, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 38599, "name": "Create a file on magnetic tape", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n"}
{"id": 38600, "name": "Sorting algorithms_Heapsort", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n"}
{"id": 38601, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 38602, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 38603, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 38604, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 38605, "name": "Euler method", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n"}
{"id": 38606, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 38607, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 38608, "name": "JortSort", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n"}
{"id": 38609, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 38610, "name": "Combinations and permutations", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n"}
{"id": 38611, "name": "Sort numbers lexicographically", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n"}
{"id": 38612, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 38613, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 38614, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 38615, "name": "Sorting algorithms_Shell sort", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 38616, "name": "Doubly-linked list_Definition", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n"}
{"id": 38617, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 38618, "name": "Permutation test", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n"}
{"id": 38619, "name": "Möbius function", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n"}
{"id": 38620, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "Python": "next = str(int('123') + 1)\n"}
{"id": 38621, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 38622, "name": "Sorting algorithms_Permutation sort", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n"}
{"id": 38623, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 38624, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 38625, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 38626, "name": "Entropy", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 38627, "name": "Tokenize a string with escaping", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n"}
{"id": 38628, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "Python": "print \"Hello world!\"\n"}
{"id": 38629, "name": "Sexy primes", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n"}
{"id": 38630, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 38631, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 38632, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 38633, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 38634, "name": "Singly-linked list_Traversal", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n", "Python": "for node in lst:\n    print node.value\n"}
{"id": 38635, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 38636, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 38637, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 38638, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 38639, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 38640, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 38641, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 38642, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 38643, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 38644, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 38645, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 38646, "name": "String interpolation (included)", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 38647, "name": "Sorting algorithms_Patience sort", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n"}
{"id": 38648, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 38649, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 38650, "name": "Tau number", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n"}
{"id": 38651, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 38652, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 38653, "name": "Partition function P", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n"}
{"id": 38654, "name": "Ray-casting algorithm", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 38655, "name": "Ray-casting algorithm", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 38656, "name": "Elliptic curve arithmetic", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 38657, "name": "Elliptic curve arithmetic", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 38658, "name": "Count occurrences of a substring", "Java": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) / subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 38659, "name": "Numbers with prime digits whose sum is 13", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 38660, "name": "Numbers with prime digits whose sum is 13", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 38661, "name": "String comparison", "Java": "public class Compare\n{\n\t\n    \n    public static void compare (String A, String B)\n    {\n        if (A.equals(B))\n            System.debug(A + ' and  ' + B + ' are lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not lexically equal.');\n\n        if (A.equalsIgnoreCase(B))\n            System.debug(A + ' and  ' + B + ' are case-insensitive lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not case-insensitive lexically equal.');\n \n        if (A.compareTo(B) < 0)\n            System.debug(A + ' is lexically before ' + B);\n        else if (A.compareTo(B) > 0)\n            System.debug(A + ' is lexically after ' + B);\n \n        if (A.compareTo(B) >= 0)\n            System.debug(A + ' is not lexically before ' + B);\n        if (A.compareTo(B) <= 0)\n            System.debug(A + ' is not lexically after ' + B);\n \n        System.debug('The lexical relationship is: ' + A.compareTo(B));\n    }\n}\n", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n"}
{"id": 38662, "name": "Take notes on the command line", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 38663, "name": "Take notes on the command line", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 38664, "name": "Thiele's interpolation formula", "Java": "import static java.lang.Math.*;\n\npublic class Test {\n    final static int N = 32;\n    final static int N2 = (N * (N - 1) / 2);\n    final static double STEP = 0.05;\n\n    static double[] xval = new double[N];\n    static double[] t_sin = new double[N];\n    static double[] t_cos = new double[N];\n    static double[] t_tan = new double[N];\n\n    static double[] r_sin = new double[N2];\n    static double[] r_cos = new double[N2];\n    static double[] r_tan = new double[N2];\n\n    static double rho(double[] x, double[] y, double[] r, int i, int n) {\n        if (n < 0)\n            return 0;\n\n        if (n == 0)\n            return y[i];\n\n        int idx = (N - 1 - n) * (N - n) / 2 + i;\n        if (r[idx] != r[idx])\n            r[idx] = (x[i] - x[i + n])\n                    / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n                    + rho(x, y, r, i + 1, n - 2);\n\n        return r[idx];\n    }\n\n    static double thiele(double[] x, double[] y, double[] r, double xin, int n) {\n        if (n > N - 1)\n            return 1;\n        return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n                + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < N; i++) {\n            xval[i] = i * STEP;\n            t_sin[i] = sin(xval[i]);\n            t_cos[i] = cos(xval[i]);\n            t_tan[i] = t_sin[i] / t_cos[i];\n        }\n\n        for (int i = 0; i < N2; i++)\n            r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN;\n\n        System.out.printf(\"%16.14f%n\", 6 * thiele(t_sin, xval, r_sin, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 3 * thiele(t_cos, xval, r_cos, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 4 * thiele(t_tan, xval, r_tan, 1.0, 0));\n    }\n}\n", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n"}
{"id": 38665, "name": "Fibonacci word", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 38666, "name": "Fibonacci word", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 38667, "name": "Angles (geometric), normalization and conversion", "Java": "import java.text.DecimalFormat;\n\n\n\npublic class AnglesNormalizationAndConversion {\n\n    public static void main(String[] args) {\n        DecimalFormat formatAngle = new DecimalFormat(\"######0.000000\");\n        DecimalFormat formatConv = new DecimalFormat(\"###0.0000\");\n        System.out.printf(\"                               degrees    gradiens        mils     radians%n\");\n        for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {\n            for ( String units : new String[] {\"degrees\", \"gradiens\", \"mils\", \"radians\"}) {\n                double d = 0, g = 0, m = 0, r = 0;\n                switch (units) {\n                case \"degrees\":\n                    d = d2d(angle);\n                    g = d2g(d);\n                    m = d2m(d);\n                    r = d2r(d);\n                    break;\n                case \"gradiens\":\n                    g = g2g(angle);\n                    d = g2d(g);\n                    m = g2m(g);\n                    r = g2r(g);\n                    break;\n                case \"mils\":\n                    m = m2m(angle);\n                    d = m2d(m);\n                    g = m2g(m);\n                    r = m2r(m);\n                    break;\n                case \"radians\":\n                    r = r2r(angle);\n                    d = r2d(r);\n                    g = r2g(r);\n                    m = r2m(r);\n                    break;\n                }\n                System.out.printf(\"%15s  %8s = %10s  %10s  %10s  %10s%n\", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));\n            }\n        }\n    }\n\n    private static final double DEGREE = 360D;\n    private static final double GRADIAN = 400D;\n    private static final double MIL = 6400D;\n    private static final double RADIAN = (2 * Math.PI);\n    \n    private static double d2d(double a) {\n        return a % DEGREE;\n    }\n    private static double d2g(double a) {\n        return a * (GRADIAN / DEGREE);\n    }\n    private static double d2m(double a) {\n        return a * (MIL / DEGREE);\n    }\n    private static double d2r(double a) {\n        return a * (RADIAN / 360);\n    }\n\n    private static double g2d(double a) {\n        return a * (DEGREE / GRADIAN);\n    }\n    private static double g2g(double a) {\n        return a % GRADIAN;\n    }\n    private static double g2m(double a) {\n        return a * (MIL / GRADIAN);\n    }\n    private static double g2r(double a) {\n        return a * (RADIAN / GRADIAN);\n    }\n    \n    private static double m2d(double a) {\n        return a * (DEGREE / MIL);\n    }\n    private static double m2g(double a) {\n        return a * (GRADIAN / MIL);\n    }\n    private static double m2m(double a) {\n        return a % MIL;\n    }\n    private static double m2r(double a) {\n        return a * (RADIAN / MIL);\n    }\n    \n    private static double r2d(double a) {\n        return a * (DEGREE / RADIAN);\n    }\n    private static double r2g(double a) {\n        return a * (GRADIAN / RADIAN);\n    }\n    private static double r2m(double a) {\n        return a * (MIL / RADIAN);\n    }\n    private static double r2r(double a) {\n        return a % RADIAN;\n    }\n    \n}\n", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n"}
{"id": 38668, "name": "Find common directory path", "Java": "public class CommonPath {\n\tpublic static String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\tfor(int i = 0; i < paths.length; i++){\n\t\t\tfolders[i] = paths[i].split(\"/\"); \n\t\t}\n\t\tfor(int j = 0; j < folders[0].length; j++){\n\t\t\tString thisFolder = folders[0][j]; \n\t\t\tboolean allMatched = true; \n\t\t\tfor(int i = 1; i < folders.length && allMatched; i++){ \n\t\t\t\tif(folders[i].length < j){ \n\t\t\t\t\tallMatched = false; \n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tallMatched &= folders[i][j].equals(thisFolder); \n\t\t\t}\n\t\t\tif(allMatched){ \n\t\t\t\tcommonPath += thisFolder + \"/\"; \n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn commonPath;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString[] paths = { \"/home/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths));\n\t\t\n\t\tString[] paths2 = { \"/hame/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths2));\n\t}\n}\n", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n"}
{"id": 38669, "name": "Verify distribution uniformity_Naive", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport java.util.function.IntSupplier;\n\npublic class Test {\n\n    static void distCheck(IntSupplier f, int nRepeats, double delta) {\n        Map<Integer, Integer> counts = new HashMap<>();\n\n        for (int i = 0; i < nRepeats; i++)\n            counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);\n\n        double target = nRepeats / (double) counts.size();\n        int deltaCount = (int) (delta / 100.0 * target);\n\n        counts.forEach((k, v) -> {\n            if (abs(target - v) >= deltaCount)\n                System.out.printf(\"distribution potentially skewed \"\n                        + \"for '%s': '%d'%n\", k, v);\n        });\n\n        counts.keySet().stream().sorted().forEach(k\n                -> System.out.printf(\"%d %d%n\", k, counts.get(k)));\n    }\n\n    public static void main(String[] a) {\n        distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);\n    }\n}\n", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n"}
{"id": 38670, "name": "Stirling numbers of the second kind", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 38671, "name": "Stirling numbers of the second kind", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 38672, "name": "Stirling numbers of the second kind", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 38673, "name": "Recaman's sequence", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 38674, "name": "Recaman's sequence", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 38675, "name": "Memory allocation", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n"}
{"id": 38676, "name": "Tic-tac-toe", "Java": "import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Hashtable;\n\npublic class TicTacToe\n{\n\tpublic static void main(String[] args)\n\t{\n\t\tTicTacToe now=new TicTacToe();\n\t\tnow.startMatch();\n\t}\n\t\n\tprivate int[][] marks;\n\tprivate int[][] wins;\n\tprivate int[] weights;\n\tprivate char[][] grid;\n\tprivate final int knotcount=3;\n\tprivate final int crosscount=4;\n\tprivate final int totalcount=5;\n\tprivate final int playerid=0;\n\tprivate final int compid=1;\n\tprivate final int truceid=2;\n\tprivate final int playingid=3;\n\tprivate String movesPlayer;\n\tprivate byte override;\n\tprivate char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};\n\tprivate char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};\n\tprivate Hashtable<Integer,Integer> crossbank;\n\tprivate Hashtable<Integer,Integer> knotbank;\n\t\n\tpublic void startMatch()\n\t{\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tSystem.out.print(\"Start?(y/n):\");\n\t\tchar choice='y';\n\t\ttry\n\t\t{\n\t\t\tchoice=br.readLine().charAt(0);\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tSystem.out.println(e.getMessage());\n\t\t}\n\t\tif(choice=='n'||choice=='N')\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tSystem.out.println(\"Use a standard numpad as an entry grid, as so:\\n \");\n\t\tdisplay(numpad);\n\t\tSystem.out.println(\"Begin\");\n\t\tint playerscore=0;\n\t\tint compscore=0;\n\t\tdo\n\t\t{\n\t\t\tint result=startGame();\n\t\t\tif(result==playerid)\n\t\t\t\tplayerscore++;\n\t\t\telse if(result==compid)\n\t\t\t\tcompscore++;\n\t\t\tSystem.out.println(\"Score: Player-\"+playerscore+\" AI-\"+compscore);\n\t\t\tSystem.out.print(\"Another?(y/n):\");\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchoice=br.readLine().charAt(0);\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\t\n\t\t}while(choice!='n'||choice=='N');\n\t\t\n\t\tSystem.out.println(\"Game over.\");\n\t}\n\tprivate void put(int cell,int player)\n\t{\n\t\tint i=-1,j=-1;;\n\t\tswitch(cell)\n\t\t{\n\t\tcase 1:i=2;j=0;break;\n\t\tcase 2:i=2;j=1;break;\n\t\tcase 3:i=2;j=2;break;\n\t\tcase 4:i=1;j=0;break;\n\t\tcase 5:i=1;j=1;break;\n\t\tcase 6:i=1;j=2;break;\n\t\tcase 7:i=0;j=0;break;\n\t\tcase 8:i=0;j=1;break;\n\t\tcase 9:i=0;j=2;break;\n\t\tdefault:display(overridegrid);return;\n\t\t}\n\t\tchar mark='x';\n\t\tif(player==0)\n\t\t\tmark='o';\n\t\tgrid[i][j]=mark;\n\t\tdisplay(grid);\n\t}\n\tprivate int startGame()\n\t{\n\t\tinit();\n\t\tdisplay(grid);\n\t\tint status=playingid;\n\t\twhile(status==playingid)\n\t\t{\n\t\t\tput(playerMove(),0);\n\t\t\tif(override==1)\n\t\t\t{\n\t\t\t\tSystem.out.println(\"O wins.\");\n\t\t\t\treturn playerid;\n\t\t\t}\n\t\t\tstatus=checkForWin();\n\t\t\tif(status!=playingid)\n\t\t\t\tbreak;\n\t\t\ttry{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}\n\t\t\tput(compMove(),1);\n\t\t\tstatus=checkForWin();\n\t\t}\n\t\treturn status;\n\t}\n\tprivate void init()\n\t{\n\t\tmovesPlayer=\"\";\n\t\toverride=0;\n\t\tmarks=new int[8][6];\n\t\twins=new int[][]\t\n\t\t{\t\n\t\t\t\t{7,8,9},\n\t\t\t\t{4,5,6},\n\t\t\t\t{1,2,3},\n\t\t\t\t{7,4,1},\n\t\t\t\t{8,5,2},\n\t\t\t\t{9,6,3},\n\t\t\t\t{7,5,3},\n\t\t\t\t{9,5,1}\n\t\t};\n\t\tweights=new int[]{3,2,3,2,4,2,3,2,3};\n\t\tgrid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};\n\t\tcrossbank=new Hashtable<Integer,Integer>();\n\t\tknotbank=new Hashtable<Integer,Integer>();\n\t}\n\tprivate void mark(int m,int player)\n\t{\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t\tfor(int j=0;j<wins[i].length;j++)\n\t\t\t\tif(wins[i][j]==m)\n\t\t\t\t{\n\t\t\t\t\tmarks[i][j]=1;\n\t\t\t\t\tif(player==playerid)\n\t\t\t\t\t\tmarks[i][knotcount]++;\n\t\t\t\t\telse\n\t\t\t\t\t\tmarks[i][crosscount]++;\n\t\t\t\t\tmarks[i][totalcount]++;\n\t\t\t\t}\n\t}\n\tprivate void fixWeights()\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tif(marks[i][j]==1)\n\t\t\t\t\tif(weights[wins[i][j]-1]!=Integer.MIN_VALUE)\n\t\t\t\t\t\tweights[wins[i][j]-1]=Integer.MIN_VALUE;\n\t\t\n\t\tfor(int i=0;i<8;i++)\n\t\t{\n\t\t\tif(marks[i][totalcount]!=2)\n\t\t\t\tcontinue;\n\t\t\tif(marks[i][crosscount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=6;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(marks[i][knotcount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=5;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprivate int compMove()\n\t{\n\t\tint cell=move();\n\t\tSystem.out.println(\"Computer plays: \"+cell);\n\t\t\n\t\treturn cell;\n\t}\n\tprivate int move()\n\t{\n\t\tint max=Integer.MIN_VALUE;\n\t\tint cell=0;\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]>max)\n\t\t\t{\n\t\t\t\tmax=weights[i];\n\t\t\t\tcell=i+1;\n\t\t\t}\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tif(movesPlayer.equals(\"76\")||movesPlayer.equals(\"67\"))\n\t\t\tcell=9;\n\t\telse if(movesPlayer.equals(\"92\")||movesPlayer.equals(\"29\"))\n\t\t\tcell=3;\n\t\telse if (movesPlayer.equals(\"18\")||movesPlayer.equals(\"81\"))\n\t\t\tcell=7;\n\t\telse if(movesPlayer.equals(\"73\")||movesPlayer.equals(\"37\"))\n\t\t\tcell=4*((int)(Math.random()*2)+1);\n\t\telse if(movesPlayer.equals(\"19\")||movesPlayer.equals(\"91\"))\n\t\t\tcell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));\n\t\t\n\t\tmark(cell,1);\n\t\tfixWeights();\n\t\tcrossbank.put(cell, 0);\n\t\treturn cell;\n\t}\n\tprivate int playerMove()\n\t{\n\t\tSystem.out.print(\"What's your move?: \");\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tint cell=0;\n\t\tint okay=0;\n\t\twhile(okay==0)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcell=Integer.parseInt(br.readLine());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\tif(cell==7494)\n\t\t\t{\n\t\t\t\toverride=1;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)\n\t\t\t\tSystem.out.print(\"Invalid move. Try again:\");\n\t\t\telse\n\t\t\t\tokay=1;\n\t\t}\n\t\tplayerMoved(cell);\n\t\tSystem.out.println();\n\t\treturn cell;\n\t}\n\tprivate void playerMoved(int cell)\n\t{\n\t\tmovesPlayer+=cell;\n\t\tmark(cell,0);\n\t\tfixWeights();\n\t\tknotbank.put(cell, 0);\n\t}\n\tprivate int checkForWin()\n\t{\n\t\tint crossflag=0,knotflag=0;\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t{\n\t\t\tif(crossbank.containsKey(wins[i][0]))\n\t\t\t\tif(crossbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(crossbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcrossflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\tif(knotbank.containsKey(wins[i][0]))\n\t\t\t\tif(knotbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(knotbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tknotflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t}\n\t\tif(knotflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"O wins.\");\n\t\t\treturn playerid;\n\t\t}\n\t\telse if(crossflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"X wins.\");\n\t\t\treturn compid;\n\t\t}\n\t\t\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]!=Integer.MIN_VALUE)\n\t\t\t\treturn playingid;\n\t\tSystem.out.println(\"Truce\");\n\t\t\n\t\treturn truceid;\n\t}\n\tprivate void display(char[][] grid)\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t{\n\t\t\tSystem.out.println(\"\\n-------\");\n\t\t\tSystem.out.print(\"|\");\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tSystem.out.print(grid[i][j]+\"|\");\n\t\t}\n\t\tSystem.out.println(\"\\n-------\");\n\t}\n}\n", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n"}
{"id": 38677, "name": "Tic-tac-toe", "Java": "import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Hashtable;\n\npublic class TicTacToe\n{\n\tpublic static void main(String[] args)\n\t{\n\t\tTicTacToe now=new TicTacToe();\n\t\tnow.startMatch();\n\t}\n\t\n\tprivate int[][] marks;\n\tprivate int[][] wins;\n\tprivate int[] weights;\n\tprivate char[][] grid;\n\tprivate final int knotcount=3;\n\tprivate final int crosscount=4;\n\tprivate final int totalcount=5;\n\tprivate final int playerid=0;\n\tprivate final int compid=1;\n\tprivate final int truceid=2;\n\tprivate final int playingid=3;\n\tprivate String movesPlayer;\n\tprivate byte override;\n\tprivate char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};\n\tprivate char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};\n\tprivate Hashtable<Integer,Integer> crossbank;\n\tprivate Hashtable<Integer,Integer> knotbank;\n\t\n\tpublic void startMatch()\n\t{\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tSystem.out.print(\"Start?(y/n):\");\n\t\tchar choice='y';\n\t\ttry\n\t\t{\n\t\t\tchoice=br.readLine().charAt(0);\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tSystem.out.println(e.getMessage());\n\t\t}\n\t\tif(choice=='n'||choice=='N')\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tSystem.out.println(\"Use a standard numpad as an entry grid, as so:\\n \");\n\t\tdisplay(numpad);\n\t\tSystem.out.println(\"Begin\");\n\t\tint playerscore=0;\n\t\tint compscore=0;\n\t\tdo\n\t\t{\n\t\t\tint result=startGame();\n\t\t\tif(result==playerid)\n\t\t\t\tplayerscore++;\n\t\t\telse if(result==compid)\n\t\t\t\tcompscore++;\n\t\t\tSystem.out.println(\"Score: Player-\"+playerscore+\" AI-\"+compscore);\n\t\t\tSystem.out.print(\"Another?(y/n):\");\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchoice=br.readLine().charAt(0);\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\t\n\t\t}while(choice!='n'||choice=='N');\n\t\t\n\t\tSystem.out.println(\"Game over.\");\n\t}\n\tprivate void put(int cell,int player)\n\t{\n\t\tint i=-1,j=-1;;\n\t\tswitch(cell)\n\t\t{\n\t\tcase 1:i=2;j=0;break;\n\t\tcase 2:i=2;j=1;break;\n\t\tcase 3:i=2;j=2;break;\n\t\tcase 4:i=1;j=0;break;\n\t\tcase 5:i=1;j=1;break;\n\t\tcase 6:i=1;j=2;break;\n\t\tcase 7:i=0;j=0;break;\n\t\tcase 8:i=0;j=1;break;\n\t\tcase 9:i=0;j=2;break;\n\t\tdefault:display(overridegrid);return;\n\t\t}\n\t\tchar mark='x';\n\t\tif(player==0)\n\t\t\tmark='o';\n\t\tgrid[i][j]=mark;\n\t\tdisplay(grid);\n\t}\n\tprivate int startGame()\n\t{\n\t\tinit();\n\t\tdisplay(grid);\n\t\tint status=playingid;\n\t\twhile(status==playingid)\n\t\t{\n\t\t\tput(playerMove(),0);\n\t\t\tif(override==1)\n\t\t\t{\n\t\t\t\tSystem.out.println(\"O wins.\");\n\t\t\t\treturn playerid;\n\t\t\t}\n\t\t\tstatus=checkForWin();\n\t\t\tif(status!=playingid)\n\t\t\t\tbreak;\n\t\t\ttry{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}\n\t\t\tput(compMove(),1);\n\t\t\tstatus=checkForWin();\n\t\t}\n\t\treturn status;\n\t}\n\tprivate void init()\n\t{\n\t\tmovesPlayer=\"\";\n\t\toverride=0;\n\t\tmarks=new int[8][6];\n\t\twins=new int[][]\t\n\t\t{\t\n\t\t\t\t{7,8,9},\n\t\t\t\t{4,5,6},\n\t\t\t\t{1,2,3},\n\t\t\t\t{7,4,1},\n\t\t\t\t{8,5,2},\n\t\t\t\t{9,6,3},\n\t\t\t\t{7,5,3},\n\t\t\t\t{9,5,1}\n\t\t};\n\t\tweights=new int[]{3,2,3,2,4,2,3,2,3};\n\t\tgrid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};\n\t\tcrossbank=new Hashtable<Integer,Integer>();\n\t\tknotbank=new Hashtable<Integer,Integer>();\n\t}\n\tprivate void mark(int m,int player)\n\t{\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t\tfor(int j=0;j<wins[i].length;j++)\n\t\t\t\tif(wins[i][j]==m)\n\t\t\t\t{\n\t\t\t\t\tmarks[i][j]=1;\n\t\t\t\t\tif(player==playerid)\n\t\t\t\t\t\tmarks[i][knotcount]++;\n\t\t\t\t\telse\n\t\t\t\t\t\tmarks[i][crosscount]++;\n\t\t\t\t\tmarks[i][totalcount]++;\n\t\t\t\t}\n\t}\n\tprivate void fixWeights()\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tif(marks[i][j]==1)\n\t\t\t\t\tif(weights[wins[i][j]-1]!=Integer.MIN_VALUE)\n\t\t\t\t\t\tweights[wins[i][j]-1]=Integer.MIN_VALUE;\n\t\t\n\t\tfor(int i=0;i<8;i++)\n\t\t{\n\t\t\tif(marks[i][totalcount]!=2)\n\t\t\t\tcontinue;\n\t\t\tif(marks[i][crosscount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=6;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(marks[i][knotcount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=5;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprivate int compMove()\n\t{\n\t\tint cell=move();\n\t\tSystem.out.println(\"Computer plays: \"+cell);\n\t\t\n\t\treturn cell;\n\t}\n\tprivate int move()\n\t{\n\t\tint max=Integer.MIN_VALUE;\n\t\tint cell=0;\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]>max)\n\t\t\t{\n\t\t\t\tmax=weights[i];\n\t\t\t\tcell=i+1;\n\t\t\t}\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tif(movesPlayer.equals(\"76\")||movesPlayer.equals(\"67\"))\n\t\t\tcell=9;\n\t\telse if(movesPlayer.equals(\"92\")||movesPlayer.equals(\"29\"))\n\t\t\tcell=3;\n\t\telse if (movesPlayer.equals(\"18\")||movesPlayer.equals(\"81\"))\n\t\t\tcell=7;\n\t\telse if(movesPlayer.equals(\"73\")||movesPlayer.equals(\"37\"))\n\t\t\tcell=4*((int)(Math.random()*2)+1);\n\t\telse if(movesPlayer.equals(\"19\")||movesPlayer.equals(\"91\"))\n\t\t\tcell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));\n\t\t\n\t\tmark(cell,1);\n\t\tfixWeights();\n\t\tcrossbank.put(cell, 0);\n\t\treturn cell;\n\t}\n\tprivate int playerMove()\n\t{\n\t\tSystem.out.print(\"What's your move?: \");\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tint cell=0;\n\t\tint okay=0;\n\t\twhile(okay==0)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcell=Integer.parseInt(br.readLine());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\tif(cell==7494)\n\t\t\t{\n\t\t\t\toverride=1;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)\n\t\t\t\tSystem.out.print(\"Invalid move. Try again:\");\n\t\t\telse\n\t\t\t\tokay=1;\n\t\t}\n\t\tplayerMoved(cell);\n\t\tSystem.out.println();\n\t\treturn cell;\n\t}\n\tprivate void playerMoved(int cell)\n\t{\n\t\tmovesPlayer+=cell;\n\t\tmark(cell,0);\n\t\tfixWeights();\n\t\tknotbank.put(cell, 0);\n\t}\n\tprivate int checkForWin()\n\t{\n\t\tint crossflag=0,knotflag=0;\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t{\n\t\t\tif(crossbank.containsKey(wins[i][0]))\n\t\t\t\tif(crossbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(crossbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcrossflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\tif(knotbank.containsKey(wins[i][0]))\n\t\t\t\tif(knotbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(knotbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tknotflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t}\n\t\tif(knotflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"O wins.\");\n\t\t\treturn playerid;\n\t\t}\n\t\telse if(crossflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"X wins.\");\n\t\t\treturn compid;\n\t\t}\n\t\t\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]!=Integer.MIN_VALUE)\n\t\t\t\treturn playingid;\n\t\tSystem.out.println(\"Truce\");\n\t\t\n\t\treturn truceid;\n\t}\n\tprivate void display(char[][] grid)\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t{\n\t\t\tSystem.out.println(\"\\n-------\");\n\t\t\tSystem.out.print(\"|\");\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tSystem.out.print(grid[i][j]+\"|\");\n\t\t}\n\t\tSystem.out.println(\"\\n-------\");\n\t}\n}\n", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n"}
{"id": 38678, "name": "Integer sequence", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 38679, "name": "Integer sequence", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 38680, "name": "Integer sequence", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 38681, "name": "Entropy_Narcissist", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n"}
{"id": 38682, "name": "Entropy_Narcissist", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n"}
{"id": 38683, "name": "DNS query", "Java": "import java.net.InetAddress;\nimport java.net.Inet4Address;\nimport java.net.Inet6Address;\nimport java.net.UnknownHostException;\n\nclass DnsQuery {\n    public static void main(String[] args) {\n        try {\n            InetAddress[] ipAddr = InetAddress.getAllByName(\"www.kame.net\");\n            for(int i=0; i < ipAddr.length ; i++) {\n                if (ipAddr[i] instanceof Inet4Address) {\n                    System.out.println(\"IPv4 : \" + ipAddr[i].getHostAddress());\n                } else if (ipAddr[i] instanceof Inet6Address) {\n                    System.out.println(\"IPv6 : \" + ipAddr[i].getHostAddress());\n                }\n            }\n        } catch (UnknownHostException uhe) {\n            System.err.println(\"unknown host\");\n        }\n    }\n}\n", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n"}
{"id": 38684, "name": "Peano curve", "Java": "import java.io.*;\n\npublic class PeanoCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"peano_curve.svg\"))) {\n            PeanoCurve s = new PeanoCurve(writer);\n            final int length = 8;\n            s.currentAngle = 90;\n            s.currentX = length;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(656);\n            s.execute(rewrite(4));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private PeanoCurve(final Writer writer) {\n        this.writer = writer;\n    }\n\n    private void begin(final int size) throws IOException {\n        write(\"<svg xmlns='http:\n        write(\"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n        write(\"<path stroke-width='1' stroke='black' fill='none' d='\");\n    }\n\n    private void end() throws IOException {\n        write(\"'/>\\n</svg>\\n\");\n    }\n\n    private void execute(final String s) throws IOException {\n        write(\"M%g,%g\\n\", currentX, currentY);\n        for (int i = 0, n = s.length(); i < n; ++i) {\n            switch (s.charAt(i)) {\n                case 'F':\n                    line(lineLength);\n                    break;\n                case '+':\n                    turn(ANGLE);\n                    break;\n                case '-':\n                    turn(-ANGLE);\n                    break;\n            }\n        }\n    }\n\n    private void line(final double length) throws IOException {\n        final double theta = (Math.PI * currentAngle) / 180.0;\n        currentX += length * Math.cos(theta);\n        currentY += length * Math.sin(theta);\n        write(\"L%g,%g\\n\", currentX, currentY);\n    }\n\n    private void turn(final int angle) {\n        currentAngle = (currentAngle + angle) % 360;\n    }\n\n    private void write(final String format, final Object... args) throws IOException {\n        writer.write(String.format(format, args));\n    }\n\n    private static String rewrite(final int order) {\n        String s = \"L\";\n        for (int i = 0; i < order; ++i) {\n            final StringBuilder sb = new StringBuilder();\n            for (int j = 0, n = s.length(); j < n; ++j) {\n                final char ch = s.charAt(j);\n                if (ch == 'L')\n                    sb.append(\"LFRFL-F-RFLFR+F+LFRFL\");\n                else if (ch == 'R')\n                    sb.append(\"RFLFR+F+LFRFL-F-RFLFR\");\n                else\n                    sb.append(ch);\n            }\n            s = sb.toString();\n        }\n        return s;\n    }\n\n    private final Writer writer;\n    private double lineLength;\n    private double currentX;\n    private double currentY;\n    private int currentAngle;\n    private static final int ANGLE = 90;\n}\n", "Python": "import turtle as tt\nimport inspect\n\nstack = [] \ndef peano(iterations=1):\n    global stack\n\n    \n    ivan = tt.Turtle(shape = \"classic\", visible = True)\n\n\n    \n    screen = tt.Screen()\n    screen.title(\"Desenhin do Peano\")\n    screen.bgcolor(\"\n    screen.delay(0) \n    screen.setup(width=0.95, height=0.9)\n\n    \n    walk = 1\n\n    def screenlength(k):\n        \n        \n        if k != 0:\n            length = screenlength(k-1)\n            return 2*length + 1\n        else: return 0\n\n    kkkj = screenlength(iterations)\n    screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)\n    ivan.color(\"\n\n\n    \n    def step1(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n    def step2(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n\n    \n    ivan.left(90)\n    step2(iterations)\n\n    tt.done()\n\nif __name__ == \"__main__\":\n    peano(4)\n    import pylab as P \n    P.plot(stack)\n    P.show()\n"}
{"id": 38685, "name": "Seven-sided dice from five-sided dice", "Java": "import java.util.Random;\npublic class SevenSidedDice \n{\n\tprivate static final Random rnd = new Random();\n\tpublic static void main(String[] args)\n\t{\n\t\tSevenSidedDice now=new SevenSidedDice();\n\t\tSystem.out.println(\"Random number from 1 to 7: \"+now.seven());\n\t}\n\tint seven()\n\t{\n\t\tint v=21;\n\t\twhile(v>20)\n\t\t\tv=five()+five()*5-6;\n\t\treturn 1+v%7;\n\t}\n\tint five()\n\t{\n\t\treturn 1+rnd.nextInt(5);\n\t}\n}\n", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n"}
{"id": 38686, "name": "Solve the no connection puzzle", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\n\npublic class NoConnection {\n\n    \n    static int[][] links = {\n        {2, 3, 4}, \n        {3, 4, 5}, \n        {2, 4},    \n        {5},       \n        {2, 3, 4}, \n        {3, 4, 5}, \n    };\n\n    static int[] pegs = new int[8];\n\n    public static void main(String[] args) {\n\n        List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());\n        do {\n            Collections.shuffle(vals);\n            for (int i = 0; i < pegs.length; i++)\n                pegs[i] = vals.get(i);\n\n        } while (!solved());\n\n        printResult();\n    }\n\n    static boolean solved() {\n        for (int i = 0; i < links.length; i++)\n            for (int peg : links[i])\n                if (abs(pegs[i] - peg) == 1)\n                    return false;\n        return true;\n    }\n\n    static void printResult() {\n        System.out.printf(\"  %s %s%n\", pegs[0], pegs[1]);\n        System.out.printf(\"%s %s %s %s%n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n        System.out.printf(\"  %s %s%n\", pegs[6], pegs[7]);\n    }\n}\n", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n"}
{"id": 38687, "name": "Solve the no connection puzzle", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\n\npublic class NoConnection {\n\n    \n    static int[][] links = {\n        {2, 3, 4}, \n        {3, 4, 5}, \n        {2, 4},    \n        {5},       \n        {2, 3, 4}, \n        {3, 4, 5}, \n    };\n\n    static int[] pegs = new int[8];\n\n    public static void main(String[] args) {\n\n        List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());\n        do {\n            Collections.shuffle(vals);\n            for (int i = 0; i < pegs.length; i++)\n                pegs[i] = vals.get(i);\n\n        } while (!solved());\n\n        printResult();\n    }\n\n    static boolean solved() {\n        for (int i = 0; i < links.length; i++)\n            for (int peg : links[i])\n                if (abs(pegs[i] - peg) == 1)\n                    return false;\n        return true;\n    }\n\n    static void printResult() {\n        System.out.printf(\"  %s %s%n\", pegs[0], pegs[1]);\n        System.out.printf(\"%s %s %s %s%n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n        System.out.printf(\"  %s %s%n\", pegs[6], pegs[7]);\n    }\n}\n", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n"}
{"id": 38688, "name": "Extensible prime generator", "Java": "import java.util.*;\n\npublic class PrimeGenerator {\n    private int limit_;\n    private int index_ = 0;\n    private int increment_;\n    private int count_ = 0;\n    private List<Integer> primes_ = new ArrayList<>();\n    private BitSet sieve_ = new BitSet();\n    private int sieveLimit_ = 0;\n\n    public PrimeGenerator(int initialLimit, int increment) {\n        limit_ = nextOddNumber(initialLimit);\n        increment_ = increment;\n        primes_.add(2);\n        findPrimes(3);\n    }\n\n    public int nextPrime() {\n        if (index_ == primes_.size()) {\n            if (Integer.MAX_VALUE - increment_ < limit_)\n                return 0;\n            int start = limit_ + 2;\n            limit_ = nextOddNumber(limit_ + increment_);\n            primes_.clear();\n            findPrimes(start);\n        }\n        ++count_;\n        return primes_.get(index_++);\n    }\n\n    public int count() {\n        return count_;\n    }\n\n    private void findPrimes(int start) {\n        index_ = 0;\n        int newLimit = sqrt(limit_);\n        for (int p = 3; p * p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p));\n            for (; q <= newLimit; q += 2*p)\n                sieve_.set(q/2 - 1, true);\n        }\n        sieveLimit_ = newLimit;\n        int count = (limit_ - start)/2 + 1;\n        BitSet composite = new BitSet(count);\n        for (int p = 3; p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start;\n            q /= 2;\n            for (; q >= 0 && q < count; q += p)\n                composite.set(q, true);\n        }\n        for (int p = 0; p < count; ++p) {\n            if (!composite.get(p))\n                primes_.add(p * 2 + start);\n        }\n    }\n\n    private static int sqrt(int n) {\n        return nextOddNumber((int)Math.sqrt(n));\n    }\n\n    private static int nextOddNumber(int n) {\n        return 1 + 2 * (n/2);\n    }\n\n    public static void main(String[] args) {\n        PrimeGenerator pgen = new PrimeGenerator(20, 200000);\n        System.out.println(\"First 20 primes:\");\n        for (int i = 0; i < 20; ++i) {\n            if (i > 0)\n                System.out.print(\", \");\n            System.out.print(pgen.nextPrime());\n        }\n        System.out.println();\n        System.out.println(\"Primes between 100 and 150:\");\n        for (int i = 0; ; ) {\n            int prime = pgen.nextPrime();\n            if (prime > 150)\n                break;\n            if (prime >= 100) {\n                if (i++ != 0)\n                    System.out.print(\", \");\n                System.out.print(prime);\n            }\n        }\n        System.out.println();\n        int count = 0;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime > 8000)\n                break;\n            if (prime >= 7700)\n                ++count;\n        }\n        System.out.println(\"Number of primes between 7700 and 8000: \" + count);\n        int n = 10000;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime == 0) {\n                System.out.println(\"Can't generate any more primes.\");\n                break;\n            }\n            if (pgen.count() == n) {\n                System.out.println(n + \"th prime: \" + prime);\n                n *= 10;\n            }\n        }\n    }\n}\n", "Python": "islice(count(7), 0, None, 2)\n"}
{"id": 38689, "name": "Rock-paper-scissors", "Java": "import java.util.Arrays;\nimport java.util.EnumMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Random;\n\npublic class RPS {\n\tpublic enum Item{\n\t\tROCK, PAPER, SCISSORS, ;\n\t\tpublic List<Item> losesToList;\n\t\tpublic boolean losesTo(Item other) {\n\t\t\treturn losesToList.contains(other);\n\t\t}\n\t\tstatic {\n\t\t\tSCISSORS.losesToList = Arrays.asList(ROCK);\n\t\t\tROCK.losesToList = Arrays.asList(PAPER);\n\t\t\tPAPER.losesToList = Arrays.asList(SCISSORS);\n\t\t\t\n                }\n\t}\n\t\n\tpublic final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{\n\t\tfor(Item item:Item.values())\n\t\t\tput(item, 1);\n\t}};\n\n\tprivate int totalThrows = Item.values().length;\n\n\tpublic static void main(String[] args){\n\t\tRPS rps = new RPS();\n\t\trps.run();\n\t}\n\n\tpublic void run() {\n\t\tScanner in = new Scanner(System.in);\n\t\tSystem.out.print(\"Make your choice: \");\n\t\twhile(in.hasNextLine()){\n\t\t\tItem aiChoice = getAIChoice();\n\t\t\tString input = in.nextLine();\n\t\t\tItem choice;\n\t\t\ttry{\n\t\t\t\tchoice = Item.valueOf(input.toUpperCase());\n\t\t\t}catch (IllegalArgumentException ex){\n\t\t\t\tSystem.out.println(\"Invalid choice\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcounts.put(choice, counts.get(choice) + 1);\n\t\t\ttotalThrows++;\n\t\t\tSystem.out.println(\"Computer chose: \" + aiChoice);\n\t\t\tif(aiChoice == choice){\n\t\t\t\tSystem.out.println(\"Tie!\");\n\t\t\t}else if(aiChoice.losesTo(choice)){\n\t\t\t\tSystem.out.println(\"You chose...wisely. You win!\");\n\t\t\t}else{\n\t\t\t\tSystem.out.println(\"You chose...poorly. You lose!\");\n\t\t\t}\n\t\t\tSystem.out.print(\"Make your choice: \");\n\t\t}\n\t}\n\n\tprivate static final Random rng = new Random();\n\tprivate Item getAIChoice() {\n\t\tint rand = rng.nextInt(totalThrows);\n\t\tfor(Map.Entry<Item, Integer> entry:counts.entrySet()){\n\t\t\tItem item = entry.getKey();\n\t\t\tint count = entry.getValue();\n\t\t\tif(rand < count){\n\t\t\t\tList<Item> losesTo = item.losesToList;\n\t\t\t\treturn losesTo.get(rng.nextInt(losesTo.size()));\n\t\t\t}\n\t\t\trand -= count;\n\t\t}\n\t\treturn null;\n\t}\n}\n", "Python": "from random import choice\n\nrules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}\nprevious = ['rock', 'paper', 'scissors']\n\nwhile True:\n    human = input('\\nchoose your weapon: ')\n    computer = rules[choice(previous)]  \n\n    if human in ('quit', 'exit'): break\n\n    elif human in rules:\n        previous.append(human)\n        print('the computer played', computer, end='; ')\n\n        if rules[computer] == human:  \n            print('yay you win!')\n        elif rules[human] == computer:  \n            print('the computer beat you... :(')\n        else: print(\"it's a tie!\")\n\n    else: print(\"that's not a valid choice\")\n"}
{"id": 38690, "name": "Create a two-dimensional array at runtime", "Java": "import java.util.Scanner;\n\npublic class twoDimArray {\n  public static void main(String[] args) {\n        Scanner in = new Scanner(System.in);\n        \n        int nbr1 = in.nextInt();\n        int nbr2 = in.nextInt();\n        \n        double[][] array = new double[nbr1][nbr2];\n        array[0][0] = 42.0;\n        System.out.println(\"The number at place [0 0] is \" + array[0][0]);\n  }\n}\n", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n"}
{"id": 38691, "name": "Chinese remainder theorem", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n"}
{"id": 38692, "name": "Chinese remainder theorem", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n"}
{"id": 38693, "name": "Vigenère cipher_Cryptanalysis", "Java": "public class Vig{\nstatic String encodedMessage =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n \nfinal static double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n \n\npublic static void main(String[] args) {\n    int lenghtOfEncodedMessage = encodedMessage.length();\n    char[] encoded = new char [lenghtOfEncodedMessage] ;\n    char[] key =  new char [lenghtOfEncodedMessage] ;\n\n    encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0);\n    int txt[] = new int[lenghtOfEncodedMessage];\n    int len = 0, j;\n\n    double fit, best_fit = 1e100;\n \n    for (j = 0; j < lenghtOfEncodedMessage; j++)\n        if (Character.isUpperCase(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n \n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        System.out.printf(\"%f, key length: %2d \", fit, j);\n            System.out.print(key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            System.out.print(\" <--- best so far\");\n        }\n        System.out.print(\"\\n\");\n\n    }\n}\n\n\n    static String decrypt(String text, final String key) {\n        String res = \"\";\n        text = text.toUpperCase();\n        for (int i = 0, j = 0; i < text.length(); i++) {\n            char c = text.charAt(i);\n            if (c < 'A' || c > 'Z') continue;\n            res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n            j = ++j % key.length();\n        }\n        return res;\n    }\n\nstatic int best_match(final double []a, final double []b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n \n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n \n    return best_rotate;\n}\n \nstatic double freq_every_nth(final int []msg, int len, int interval, char[] key) {\n    double sum, d, ret;\n    double  [] accu = new double [26];\n    double  [] out = new double [26];\n    int i, j, rot;\n \n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n\trot = best_match(out, freq);\n\ttry{\n            key[j] = (char)(rot + 'A');\n\t} catch (Exception e) {\n\t\tSystem.out.print(e.getMessage());\n\t}\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n \n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n \n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n \n    key[interval] = '\\0';\n    return ret;\n}\n \n}\n", "Python": "from string import uppercase\nfrom operator import itemgetter\n\ndef vigenere_decrypt(target_freqs, input):\n    nchars = len(uppercase)\n    ordA = ord('A')\n    sorted_targets = sorted(target_freqs)\n\n    def frequency(input):\n        result = [[c, 0.0] for c in uppercase]\n        for c in input:\n            result[c - ordA][1] += 1\n        return result\n\n    def correlation(input):\n        result = 0.0\n        freq = frequency(input)\n        freq.sort(key=itemgetter(1))\n\n        for i, f in enumerate(freq):\n            result += f[1] * sorted_targets[i]\n        return result\n\n    cleaned = [ord(c) for c in input.upper() if c.isupper()]\n    best_len = 0\n    best_corr = -100.0\n\n    \n    \n    for i in xrange(2, len(cleaned) // 20):\n        pieces = [[] for _ in xrange(i)]\n        for j, c in enumerate(cleaned):\n            pieces[j % i].append(c)\n\n        \n        \n        corr = -0.5 * i + sum(correlation(p) for p in pieces)\n\n        if corr > best_corr:\n            best_len = i\n            best_corr = corr\n\n    if best_len == 0:\n        return (\"Text is too short to analyze\", \"\")\n\n    pieces = [[] for _ in xrange(best_len)]\n    for i, c in enumerate(cleaned):\n        pieces[i % best_len].append(c)\n\n    freqs = [frequency(p) for p in pieces]\n\n    key = \"\"\n    for fr in freqs:\n        fr.sort(key=itemgetter(1), reverse=True)\n\n        m = 0\n        max_corr = 0.0\n        for j in xrange(nchars):\n            corr = 0.0\n            c = ordA + j\n            for frc in fr:\n                d = (ord(frc[0]) - c + nchars) % nchars\n                corr += frc[1] * target_freqs[d]\n\n            if corr > max_corr:\n                m = j\n                max_corr = corr\n\n        key += chr(m + ordA)\n\n    r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)\n         for i, c in enumerate(cleaned))\n    return (key, \"\".join(r))\n\n\ndef main():\n    encoded = \n\n    english_frequences = [\n        0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n        0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n        0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n        0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\n    (key, decoded) = vigenere_decrypt(english_frequences, encoded)\n    print \"Key:\", key\n    print \"\\nText:\", decoded\n\nmain()\n"}
{"id": 38694, "name": "Pi", "Java": "import java.math.BigInteger ;\n\npublic class Pi {\n  final BigInteger TWO = BigInteger.valueOf(2) ;\n  final BigInteger THREE = BigInteger.valueOf(3) ;\n  final BigInteger FOUR = BigInteger.valueOf(4) ;\n  final BigInteger SEVEN = BigInteger.valueOf(7) ;\n\n  BigInteger q = BigInteger.ONE ;\n  BigInteger r = BigInteger.ZERO ;\n  BigInteger t = BigInteger.ONE ;\n  BigInteger k = BigInteger.ONE ;\n  BigInteger n = BigInteger.valueOf(3) ;\n  BigInteger l = BigInteger.valueOf(3) ;\n\n  public void calcPiDigits(){\n    BigInteger nn, nr ;\n    boolean first = true ;\n    while(true){\n        if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){\n          System.out.print(n) ;\n          if(first){System.out.print(\".\") ; first = false ;}\n          nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ;\n          n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ;\n          q = q.multiply(BigInteger.TEN) ;\n          r = nr ;\n          System.out.flush() ;\n        }else{\n          nr = TWO.multiply(q).add(r).multiply(l) ;\n          nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ;\n          q = q.multiply(k) ;\n          t = t.multiply(l) ;\n          l = l.add(TWO) ;\n          k = k.add(BigInteger.ONE) ;\n          n = nn ;\n          r = nr ;\n        }\n    }\n  }\n\n  public static void main(String[] args) {\n    Pi p = new Pi() ;\n    p.calcPiDigits() ;\n  }\n}\n", "Python": "def calcPi():\n    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n    while True:\n        if 4*q+r-t < n*t:\n            yield n\n            nr = 10*(r-n*t)\n            n  = ((10*(3*q+r))//t)-10*n\n            q  *= 10\n            r  = nr\n        else:\n            nr = (2*q+r)*l\n            nn = (q*(7*k)+2+(r*l))//(t*l)\n            q  *= k\n            t  *= l\n            l  += 2\n            k += 1\n            n  = nn\n            r  = nr\n\nimport sys\npi_digits = calcPi()\ni = 0\nfor d in pi_digits:\n    sys.stdout.write(str(d))\n    i += 1\n    if i == 40: print(\"\"); i = 0\n"}
{"id": 38695, "name": "Hofstadter Q sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n"}
{"id": 38696, "name": "Hofstadter Q sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n"}
{"id": 38697, "name": "Y combinator", "Java": "import java.util.function.Function;\n\npublic interface YCombinator {\n  interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }\n  public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {\n    RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));\n    return r.apply(r);\n  }\n\n  public static void main(String... arguments) {\n    Function<Integer,Integer> fib = Y(f -> n ->\n      (n <= 2)\n        ? 1\n        : (f.apply(n - 1) + f.apply(n - 2))\n    );\n    Function<Integer,Integer> fac = Y(f -> n ->\n      (n <= 1)\n        ? 1\n        : (n * f.apply(n - 1))\n    );\n\n    System.out.println(\"fib(10) = \" + fib.apply(10));\n    System.out.println(\"fac(10) = \" + fac.apply(10));\n  }\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))\n>>> [ Y(fac)(i) for i in range(10) ]\n[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]\n>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))\n>>> [ Y(fib)(i) for i in range(10) ]\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 38698, "name": "Return multiple values", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\n\npublic class RReturnMultipleVals {\n  public static final String K_lipsum = \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n  public static final Long   K_1024   = 1024L;\n  public static final String L        = \"L\";\n  public static final String R        = \"R\";\n\n  \n  public static void main(String[] args) throws NumberFormatException{\n    Long nv_;\n    String sv_;\n    switch (args.length) {\n      case 0:\n        nv_ = K_1024;\n        sv_ = K_lipsum;\n        break;\n      case 1:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = K_lipsum;\n        break;\n      case 2:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        break;\n      default:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        for (int ix = 2; ix < args.length; ++ix) {\n          sv_ = sv_ + \" \" + args[ix];\n        }\n        break;\n    }\n\n    RReturnMultipleVals lcl = new RReturnMultipleVals();\n\n    Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); \n    System.out.println(\"Results extracted from a composite object:\");\n    System.out.printf(\"%s, %s%n%n\", rvp.getLeftVal(), rvp.getRightVal());\n\n    List<Object> rvl = lcl.getPairFromList(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"List\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvl.get(0), rvl.get(1));\n\n    Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"Map\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvm.get(L), rvm.get(R));\n  }\n  \n  \n  \n  public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {\n    return new Pair<T, U>(vl_, vr_);\n  }\n  \n  \n  \n  public List<Object> getPairFromList(Object nv_, Object sv_) {\n    List<Object> rset = new ArrayList<Object>();\n    rset.add(nv_);\n    rset.add(sv_);\n    return rset;\n  }\n  \n  \n  \n  public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {\n    Map<String, Object> rset = new HashMap<String, Object>();\n    rset.put(L, nv_);\n    rset.put(R, sv_);\n    return rset;\n  }\n\n  \n  private static class Pair<L, R> {\n    private L leftVal;\n    private R rightVal;\n\n    public Pair(L nv_, R sv_) {\n      setLeftVal(nv_);\n      setRightVal(sv_);\n    }\n    public void setLeftVal(L nv_) {\n      leftVal = nv_;\n    }\n    public L getLeftVal() {\n      return leftVal;\n    }\n    public void setRightVal(R sv_) {\n      rightVal = sv_;\n    }\n    public R getRightVal() {\n      return rightVal;\n    }\n  }\n}\n", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 38699, "name": "Van Eck sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n"}
{"id": 38700, "name": "Van Eck sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n"}
{"id": 38701, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 38702, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 38703, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38704, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38705, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 38706, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 38707, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38708, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38709, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 38710, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 38711, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 38712, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 38713, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 38714, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 38715, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 38716, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 38717, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n"}
{"id": 38718, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n"}
{"id": 38719, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 38720, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 38721, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 38722, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 38723, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 38724, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 38725, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 38726, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 38727, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 38728, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 38729, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n"}
{"id": 38730, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n"}
{"id": 38731, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n"}
{"id": 38732, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n"}
{"id": 38733, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 38734, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 38735, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 38736, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 38737, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n"}
{"id": 38738, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n"}
{"id": 38739, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n"}
{"id": 38740, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n"}
{"id": 38741, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 38742, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 38743, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 38744, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 38745, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 38746, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 38747, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 38748, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 38749, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 38750, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 38751, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 38752, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 38753, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 38754, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 38755, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 38756, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 38757, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n"}
{"id": 38758, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n"}
{"id": 38759, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 38760, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 38761, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 38762, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 38763, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 38764, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 38765, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n"}
{"id": 38766, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n"}
{"id": 38767, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 38768, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 38769, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 38770, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 38771, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 38772, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 38773, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 38774, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 38775, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 38776, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 38777, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 38778, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 38779, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 38780, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 38781, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 38782, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 38783, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 38784, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 38785, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 38786, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 38787, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 38788, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 38789, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n"}
{"id": 38790, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n"}
{"id": 38791, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 38792, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 38793, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 38794, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 38795, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 38796, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 38797, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n"}
{"id": 38798, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n"}
{"id": 38799, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 38800, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 38801, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n"}
{"id": 38802, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n"}
{"id": 38803, "name": "Hello world_Text", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 38804, "name": "Hello world_Text", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 38805, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 38806, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 38807, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 38808, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 38809, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 38810, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 38811, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 38812, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 38813, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38814, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38815, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 38816, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 38817, "name": "Discordian date", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 38818, "name": "Discordian date", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 38819, "name": "String interpolation (included)", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n"}
{"id": 38820, "name": "Bitwise operations", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n"}
{"id": 38821, "name": "Dragon curve", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n"}
{"id": 38822, "name": "Read a file line by line", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n"}
{"id": 38823, "name": "Doubly-linked list_Element insertion", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n"}
{"id": 38824, "name": "Quickselect algorithm", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n"}
{"id": 38825, "name": "Non-decimal radices_Convert", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 38826, "name": "Walk a directory_Recursively", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n"}
{"id": 38827, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 38828, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 38829, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 38830, "name": "Classes", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 38831, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 38832, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 38833, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 38834, "name": "LZW compression", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n"}
{"id": 38835, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 38836, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 38837, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 38838, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 38839, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 38840, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 38841, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n"}
{"id": 38842, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 38843, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 38844, "name": "Longest string challenge", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n"}
{"id": 38845, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 38846, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 38847, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 38848, "name": "Create a file", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 38849, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 38850, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 38851, "name": "Dining philosophers", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n"}
{"id": 38852, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 38853, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 38854, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 38855, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 38856, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 38857, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 38858, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 38859, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n"}
{"id": 38860, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n"}
{"id": 38861, "name": "Optional parameters", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n"}
{"id": 38862, "name": "Call a foreign-language function", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n"}
{"id": 38863, "name": "Faulhaber's triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 38864, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 38865, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 38866, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 38867, "name": "Word wheel", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n"}
{"id": 38868, "name": "Array concatenation", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 38869, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 38870, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 38871, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 38872, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 38873, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 38874, "name": "Primes - allocate descendants to their ancestors", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n"}
{"id": 38875, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 38876, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 38877, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 38878, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n"}
{"id": 38879, "name": "XML_Output", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n"}
{"id": 38880, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 38881, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 38882, "name": "Regular expressions", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 38883, "name": "Hash from two arrays", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n"}
{"id": 38884, "name": "Colour pinstripe_Display", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n"}
{"id": 38885, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n"}
{"id": 38886, "name": "Animate a pendulum", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n"}
{"id": 38887, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 38888, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 38889, "name": "Playing cards", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 38890, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "VB": "Option Base {0|1}\n"}
{"id": 38891, "name": "Sierpinski carpet", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 38892, "name": "Sorting algorithms_Bogosort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n"}
{"id": 38893, "name": "Euler method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n"}
{"id": 38894, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 38895, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 38896, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 38897, "name": "JortSort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n"}
{"id": 38898, "name": "Leap year", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n"}
{"id": 38899, "name": "Combinations and permutations", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n"}
{"id": 38900, "name": "Sort numbers lexicographically", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n"}
{"id": 38901, "name": "Number names", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n"}
{"id": 38902, "name": "Sorting algorithms_Shell sort", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n"}
{"id": 38903, "name": "Doubly-linked list_Definition", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n"}
{"id": 38904, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n"}
{"id": 38905, "name": "Increment a numerical string", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 38906, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 38907, "name": "Averages_Arithmetic mean", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n"}
{"id": 38908, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 38909, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 38910, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 38911, "name": "Tokenize a string with escaping", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n"}
{"id": 38912, "name": "Forward difference", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n"}
{"id": 38913, "name": "Primality by trial division", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n"}
{"id": 38914, "name": "Evaluate binomial coefficients", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 38915, "name": "Collections", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 38916, "name": "Singly-linked list_Traversal", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n"}
{"id": 38917, "name": "Bitwise operations", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 38918, "name": "Dragon curve", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n"}
{"id": 38919, "name": "Read a file line by line", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38920, "name": "Doubly-linked list_Element insertion", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 38921, "name": "Smarandache prime-digital sequence", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n"}
{"id": 38922, "name": "Quickselect algorithm", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 38923, "name": "Non-decimal radices_Convert", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 38924, "name": "Walk a directory_Recursively", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 38925, "name": "State name puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n"}
{"id": 38926, "name": "State name puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n"}
{"id": 38927, "name": "CRC-32", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 38928, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 38929, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 38930, "name": "Classes", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 38931, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 38932, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 38933, "name": "LZW compression", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n"}
{"id": 38934, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 38935, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 38936, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 38937, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 38938, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 38939, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 38940, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 38941, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 38942, "name": "Mertens function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n"}
{"id": 38943, "name": "Order by pair comparisons", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n"}
{"id": 38944, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 38945, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 38946, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 38947, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 38948, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 38949, "name": "Anonymous recursion", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 38950, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 38951, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 38952, "name": "Legendre prime counting function", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n"}
{"id": 38953, "name": "Use another language to call a function", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n"}
{"id": 38954, "name": "Longest string challenge", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 38955, "name": "Longest string challenge", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 38956, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 38957, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 38958, "name": "Unprimeable numbers", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 38959, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 38960, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 38961, "name": "Chernick's Carmichael numbers", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n"}
{"id": 38962, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 38963, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 38964, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 38965, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 38966, "name": "Sequence of primorial primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n"}
{"id": 38967, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 38968, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 38969, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 38970, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 38971, "name": "Dining philosophers", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n"}
{"id": 38972, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 38973, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 38974, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 38975, "name": "Logistic curve fitting in epidemiology", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n"}
{"id": 38976, "name": "Sorting algorithms_Strand sort", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n"}
{"id": 38977, "name": "Additive primes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n"}
{"id": 38978, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 38979, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 38980, "name": "Delegates", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n"}
{"id": 38981, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 38982, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 38983, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 38984, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 38985, "name": "Enforced immutability", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n"}
{"id": 38986, "name": "Sutherland-Hodgman polygon clipping", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n"}
{"id": 38987, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 38988, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 38989, "name": "Spiral matrix", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n"}
{"id": 38990, "name": "Optional parameters", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n"}
{"id": 38991, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 38992, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 38993, "name": "Call a foreign-language function", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 38994, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 38995, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 38996, "name": "Faulhaber's triangle", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n"}
{"id": 38997, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 38998, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 38999, "name": "Array concatenation", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 39000, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 39001, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 39002, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 39003, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 39004, "name": "Primes - allocate descendants to their ancestors", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n"}
{"id": 39005, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 39006, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 39007, "name": "First-class functions", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n"}
{"id": 39008, "name": "Proper divisors", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 39009, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n"}
{"id": 39010, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n"}
{"id": 39011, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 39012, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 39013, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 39014, "name": "Regular expressions", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 39015, "name": "Guess the number_With feedback (player)", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n"}
{"id": 39016, "name": "Guess the number_With feedback (player)", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n"}
{"id": 39017, "name": "Hash from two arrays", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 39018, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 39019, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 39020, "name": "Fractal tree", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n"}
{"id": 39021, "name": "Colour pinstripe_Display", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 39022, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 39023, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 39024, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 39025, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n"}
{"id": 39026, "name": "Animate a pendulum", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n"}
{"id": 39027, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 39028, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 39029, "name": "Create a file on magnetic tape", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n"}
{"id": 39030, "name": "Sorting algorithms_Heapsort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n"}
{"id": 39031, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 39032, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 39033, "name": "Sierpinski carpet", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 39034, "name": "Sorting algorithms_Bogosort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 39035, "name": "Euler method", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n"}
{"id": 39036, "name": "Sequence of non-squares", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 39037, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 39038, "name": "JortSort", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n"}
{"id": 39039, "name": "Leap year", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 39040, "name": "Combinations and permutations", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n"}
{"id": 39041, "name": "Sort numbers lexicographically", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n"}
{"id": 39042, "name": "Number names", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 39043, "name": "Compare length of two strings", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 39044, "name": "Sorting algorithms_Shell sort", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n"}
{"id": 39045, "name": "Doubly-linked list_Definition", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 39046, "name": "Letter frequency", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 39047, "name": "Permutation test", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n"}
{"id": 39048, "name": "Möbius function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n"}
{"id": 39049, "name": "Increment a numerical string", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 39050, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 39051, "name": "Sorting algorithms_Permutation sort", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n"}
{"id": 39052, "name": "Averages_Arithmetic mean", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 39053, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 39054, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 39055, "name": "Entropy", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n"}
{"id": 39056, "name": "Tokenize a string with escaping", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n"}
{"id": 39057, "name": "Hello world_Text", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 39058, "name": "Sexy primes", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 39059, "name": "Sexy primes", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 39060, "name": "Forward difference", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 39061, "name": "Primality by trial division", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 39062, "name": "Evaluate binomial coefficients", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 39063, "name": "Collections", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 39064, "name": "Collections", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 39065, "name": "Singly-linked list_Traversal", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n"}
{"id": 39066, "name": "Bitmap_Write a PPM file", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 39067, "name": "Delete a file", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 39068, "name": "Discordian date", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 39069, "name": "Flipping bits game", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 39070, "name": "Flipping bits game", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 39071, "name": "Hickerson series of almost integers", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 39072, "name": "Hickerson series of almost integers", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 39073, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 39074, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 39075, "name": "String interpolation (included)", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n"}
{"id": 39076, "name": "Sorting algorithms_Patience sort", "C++": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <iterator>\n#include <algorithm>\n#include <cassert>\n\ntemplate <class E>\nstruct pile_less {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() < pile2.top();\n  }\n};\n\ntemplate <class E>\nstruct pile_greater {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() > pile2.top();\n  }\n};\n\n\ntemplate <class Iterator>\nvoid patience_sort(Iterator first, Iterator last) {\n  typedef typename std::iterator_traits<Iterator>::value_type E;\n  typedef std::stack<E> Pile;\n\n  std::vector<Pile> piles;\n  \n  for (Iterator it = first; it != last; it++) {\n    E& x = *it;\n    Pile newPile;\n    newPile.push(x);\n    typename std::vector<Pile>::iterator i =\n      std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());\n    if (i != piles.end())\n      i->push(x);\n    else\n      piles.push_back(newPile);\n  }\n\n  \n  \n  std::make_heap(piles.begin(), piles.end(), pile_greater<E>());\n  for (Iterator it = first; it != last; it++) {\n    std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());\n    Pile &smallPile = piles.back();\n    *it = smallPile.top();\n    smallPile.pop();\n    if (smallPile.empty())\n      piles.pop_back();\n    else\n      std::push_heap(piles.begin(), piles.end(), pile_greater<E>());\n  }\n  assert(piles.empty());\n}\n\nint main() {\n  int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n  patience_sort(a, a+sizeof(a)/sizeof(*a));\n  std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  return 0;\n}\n", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n"}
{"id": 39077, "name": "Bioinformatics_Sequence mutation", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 39078, "name": "Bioinformatics_Sequence mutation", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 39079, "name": "Tau number", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"The first \" << limit << \" tau numbers are:\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            std::cout << std::setw(6) << n;\n            ++count;\n            if (count % 10 == 0)\n                std::cout << '\\n';\n        }\n    }\n}\n", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n"}
{"id": 39080, "name": "Determinant and permanent", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 39081, "name": "Determinant and permanent", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 39082, "name": "Determinant and permanent", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 39083, "name": "Partition function P", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n"}
{"id": 39084, "name": "Ray-casting algorithm", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nconst double epsilon = numeric_limits<float>().epsilon();\nconst numeric_limits<double> DOUBLE;\nconst double MIN = DOUBLE.min();\nconst double MAX = DOUBLE.max();\n\nstruct Point { const double x, y; };\n\nstruct Edge {\n    const Point a, b;\n\n    bool operator()(const Point& p) const\n    {\n        if (a.y > b.y) return Edge{ b, a }(p);\n        if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });\n        if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;\n        if (p.x < min(a.x, b.x)) return true;\n        auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;\n        auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;\n        return blue >= red;\n    }\n};\n\nstruct Figure {\n    const string  name;\n    const initializer_list<Edge> edges;\n\n    bool contains(const Point& p) const\n    {\n        auto c = 0;\n        for (auto e : edges) if (e(p)) c++;\n        return c % 2 != 0;\n    }\n\n    template<unsigned char W = 3>\n    void check(const initializer_list<Point>& points, ostream& os) const\n    {\n        os << \"Is point inside figure \" << name <<  '?' << endl;\n        for (auto p : points)\n            os << \"  (\" << setw(W) << p.x << ',' << setw(W) << p.y << \"): \" << boolalpha << contains(p) << endl;\n        os << endl;\n    }\n};\n\nint main()\n{\n    const initializer_list<Point> points =  { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };\n    const Figure square = { \"Square\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }\n    };\n\n    const Figure square_hole = { \"Square hole\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},\n           {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure strange = { \"Strange\",\n        {  {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},\n           {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure exagon = { \"Exagon\",\n        {  {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},\n           {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}\n        }\n    };\n\n    for(auto f : {square, square_hole, strange, exagon})\n        f.check(points, cout);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n"}
{"id": 39085, "name": "Elliptic curve arithmetic", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n"}
{"id": 39086, "name": "Elliptic curve arithmetic", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n"}
{"id": 39087, "name": "Count occurrences of a substring", "C++": "#include <iostream>\n#include <string>\n\n\nint countSubstring(const std::string& str, const std::string& sub)\n{\n    if (sub.length() == 0) return 0;\n    int count = 0;\n    for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n    {\n        ++count;\n    }\n    return count;\n}\n\nint main()\n{\n    std::cout << countSubstring(\"the three truths\", \"th\")    << '\\n';\n    std::cout << countSubstring(\"ababababab\", \"abab\")        << '\\n';\n    std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n    return 0;\n}\n", "Java": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) / subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n"}
{"id": 39088, "name": "Numbers with prime digits whose sum is 13", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 39089, "name": "Bitwise operations", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 39090, "name": "Dragon curve", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n"}
{"id": 39091, "name": "Read a file line by line", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 39092, "name": "Doubly-linked list_Element insertion", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n"}
{"id": 39093, "name": "Quickselect algorithm", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n"}
{"id": 39094, "name": "Non-decimal radices_Convert", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 39095, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 39096, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 39097, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 39098, "name": "Classes", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 39099, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 39100, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 39101, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 39102, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 39103, "name": "Anonymous recursion", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 39104, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 39105, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 39106, "name": "Create a file", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 39107, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 39108, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 39109, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 39110, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 39111, "name": "Spiral matrix", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n"}
{"id": 39112, "name": "Faulhaber's triangle", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n"}
{"id": 39113, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 39114, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 39115, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 39116, "name": "User input_Text", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 39117, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 39118, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 39119, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 39120, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 39121, "name": "First-class functions", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 39122, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 39123, "name": "XML_Output", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n"}
{"id": 39124, "name": "Regular expressions", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 39125, "name": "Guess the number_With feedback (player)", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n"}
{"id": 39126, "name": "Hash from two arrays", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 39127, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 39128, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 39129, "name": "Animate a pendulum", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n"}
{"id": 39130, "name": "Sorting algorithms_Heapsort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 39131, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 39132, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 39133, "name": "Sierpinski carpet", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 39134, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 39135, "name": "Merge and aggregate datasets", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n"}
{"id": 39136, "name": "Euler method", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 39137, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 39138, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 39139, "name": "JortSort", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n"}
{"id": 39140, "name": "Leap year", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 39141, "name": "Sort numbers lexicographically", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n"}
{"id": 39142, "name": "Number names", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 39143, "name": "Compare length of two strings", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 39144, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 39145, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 39146, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 39147, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 39148, "name": "Averages_Arithmetic mean", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 39149, "name": "Entropy", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n"}
{"id": 39150, "name": "Tokenize a string with escaping", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n"}
{"id": 39151, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n"}
{"id": 39152, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 39153, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 39154, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 39155, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 39156, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 39157, "name": "Singly-linked list_Traversal", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 39158, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 39159, "name": "Delete a file", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 39160, "name": "Discordian date", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n"}
{"id": 39161, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 39162, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 39163, "name": "String interpolation (included)", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 39164, "name": "String interpolation (included)", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 39165, "name": "Partition function P", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n"}
{"id": 39166, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 39167, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 39168, "name": "Take notes on the command line", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 39169, "name": "Angles (geometric), normalization and conversion", "C#": "using System;\n\npublic static class Angles\n{\n    public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);\n\n    public static void Print(params double[] angles) {\n        string[] names = { \"Degrees\", \"Gradians\", \"Mils\", \"Radians\" };\n        Func<double, double> rnd = a => Math.Round(a, 4);\n        Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };\n\n        Func<double, double>[,] convert = {\n            { a => a, DegToGrad, DegToMil, DegToRad },\n            { GradToDeg, a => a, GradToMil, GradToRad },\n            { MilToDeg, MilToGrad, a => a, MilToRad },\n            { RadToDeg, RadToGrad, RadToMil, a => a }\n        };\n\n        Console.WriteLine($@\"{\"Angle\",-12}{\"Normalized\",-12}{\"Unit\",-12}{\n            \"Degrees\",-12}{\"Gradians\",-12}{\"Mils\",-12}{\"Radians\",-12}\");\n\n        foreach (double angle in angles) {\n            for (int i = 0; i < 4; i++) {\n                double nAngle = normal[i](angle);\n\n                Console.WriteLine($@\"{\n                    rnd(angle),-12}{\n                    rnd(nAngle),-12}{\n                    names[i],-12}{\n                    rnd(convert[i, 0](nAngle)),-12}{\n                    rnd(convert[i, 1](nAngle)),-12}{\n                    rnd(convert[i, 2](nAngle)),-12}{\n                    rnd(convert[i, 3](nAngle)),-12}\");\n            }\n        }\n    }\n\n    public static double NormalizeDeg(double angle) => Normalize(angle, 360);\n    public static double NormalizeGrad(double angle) => Normalize(angle, 400);\n    public static double NormalizeMil(double angle) => Normalize(angle, 6400);\n    public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);\n\n    private static double Normalize(double angle, double N) {\n        while (angle <= -N) angle += N;\n        while (angle >= N) angle -= N;\n        return angle;\n    }\n\n    public static double DegToGrad(double angle) => angle * 10 / 9;\n    public static double DegToMil(double angle) => angle * 160 / 9;\n    public static double DegToRad(double angle) => angle * Math.PI / 180;\n    \n    public static double GradToDeg(double angle) => angle * 9 / 10;\n    public static double GradToMil(double angle) => angle * 16;\n    public static double GradToRad(double angle) => angle * Math.PI / 200;\n    \n    public static double MilToDeg(double angle) => angle * 9 / 160;\n    public static double MilToGrad(double angle) => angle / 16;\n    public static double MilToRad(double angle) => angle * Math.PI / 3200;\n    \n    public static double RadToDeg(double angle) => angle * 180 / Math.PI;\n    public static double RadToGrad(double angle) => angle * 200 / Math.PI;\n    public static double RadToMil(double angle) => angle * 3200 / Math.PI;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n"}
{"id": 39170, "name": "Find common directory path", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n"}
{"id": 39171, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 39172, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 39173, "name": "Memory allocation", "C#": "using System;\nusing System.Runtime.InteropServices;\n\npublic unsafe class Program\n{\n    public static unsafe void HeapMemory()\n    {\n        const int HEAP_ZERO_MEMORY = 0x00000008;\n        const int size = 1000;\n        int ph = GetProcessHeap();\n        void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);\n        if (pointer == null)\n            throw new OutOfMemoryException();\n        Console.WriteLine(HeapSize(ph, 0, pointer));\n        HeapFree(ph, 0, pointer);\n    }\n\n    public static unsafe void StackMemory()\n    {\n        byte* buffer = stackalloc byte[1000];\n        \n    }\n    public static void Main(string[] args)\n    {\n        HeapMemory();\n        StackMemory();\n    }\n    [DllImport(\"kernel32\")]\n    static extern void* HeapAlloc(int hHeap, int flags, int size);\n    [DllImport(\"kernel32\")]\n    static extern bool HeapFree(int hHeap, int flags, void* block);\n    [DllImport(\"kernel32\")]\n    static extern int GetProcessHeap();\n    [DllImport(\"kernel32\")]\n    static extern int HeapSize(int hHeap, int flags, void* block);\n\n}\n", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n"}
{"id": 39174, "name": "Tic-tac-toe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaTicTacToe\n{\n  class Program\n  {\n\n    \n    static string[][] Players = new string[][] { \n      new string[] { \"COMPUTER\", \"X\" }, \n      new string[] { \"HUMAN\", \"O\" }     \n    };\n\n    const int Unplayed = -1;\n    const int Computer = 0;\n    const int Human = 1;\n\n    \n    static int[] GameBoard = new int[9];\n\n    static int[] corners = new int[] { 0, 2, 6, 8 };\n\n    static int[][] wins = new int[][] { \n      new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, \n      new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, \n      new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };\n\n\n    \n    static void Main(string[] args)\n    {\n      while (true)\n      {\n        Console.Clear();\n        Console.WriteLine(\"Welcome to Rosetta Code Tic-Tac-Toe for C#.\");\n        initializeGameBoard();\n        displayGameBoard();\n        int currentPlayer = rnd.Next(0, 2);  \n        Console.WriteLine(\"The first move goes to {0} who is playing {1}s.\\n\", playerName(currentPlayer), playerToken(currentPlayer));\n        while (true)\n        {\n          int thisMove = getMoveFor(currentPlayer);\n          if (thisMove == Unplayed)\n          {\n            Console.WriteLine(\"{0}, you've quit the game ... am I that good?\", playerName(currentPlayer));\n            break;\n          }\n          playMove(thisMove, currentPlayer);\n          displayGameBoard();\n          if (isGameWon())\n          {\n            Console.WriteLine(\"{0} has won the game!\", playerName(currentPlayer));\n            break;\n          }\n          else if (isGameTied())\n          {\n            Console.WriteLine(\"Cat game ... we have a tie.\");\n            break;\n          }\n          currentPlayer = getNextPlayer(currentPlayer);\n        }\n        if (!playAgain())\n          return;\n      }\n    }\n\n    \n    static int getMoveFor(int player)\n    {\n      if (player == Human)\n        return getManualMove(player);\n      else\n      {\n        \n        \n        int selectedMove = getSemiRandomMove(player);\n        \n        Console.WriteLine(\"{0} selects position {1}.\", playerName(player), selectedMove + 1);\n        return selectedMove;\n      }\n    }\n\n    static int getManualMove(int player)\n    {\n      while (true)\n      {\n        Console.Write(\"{0}, enter you move (number): \", playerName(player));\n        ConsoleKeyInfo keyInfo = Console.ReadKey();\n        Console.WriteLine();  \n        if (keyInfo.Key == ConsoleKey.Escape)\n          return Unplayed;\n        if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)\n        {\n          int move = keyInfo.KeyChar - '1';  \n          if (GameBoard[move] == Unplayed)\n            return move;\n          else\n            Console.WriteLine(\"Spot {0} is already taken, please select again.\", move + 1);\n        }\n        else\n          Console.WriteLine(\"Illegal move, please select again.\\n\");\n      }\n    }\n\n    static int getRandomMove(int player)\n    {\n      int movesLeft = GameBoard.Count(position => position == Unplayed);\n      int x = rnd.Next(0, movesLeft);\n      for (int i = 0; i < GameBoard.Length; i++)  \n      {\n        if (GameBoard[i] == Unplayed && x < 0)    \n          return i;\n        x--;\n      }\n      return Unplayed;\n    }\n\n    \n    static int getSemiRandomMove(int player)\n    {\n      int posToPlay;\n      if (checkForWinningMove(player, out posToPlay))\n        return posToPlay;\n      if (checkForBlockingMove(player, out posToPlay))\n        return posToPlay;\n      return getRandomMove(player);\n    }\n\n    \n    static int getBestMove(int player)\n    {\n      return -1;\n    }\n\n    static bool checkForWinningMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(player, line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool checkForBlockingMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)\n    {\n      int cnt = 0;\n      posToPlay = int.MinValue;\n      foreach (int pos in line)\n      {\n        if (GameBoard[pos] == player)\n          cnt++;\n        else if (GameBoard[pos] == Unplayed)\n          posToPlay = pos;\n      }\n      return cnt == 2 && posToPlay >= 0;\n    }\n\n    static void playMove(int boardPosition, int player)\n    {\n      GameBoard[boardPosition] = player;\n    }\n\n    static bool isGameWon()\n    {\n      return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));\n    }\n\n    static bool takenBySamePlayer(int a, int b, int c)\n    {\n      return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];\n    }\n\n    static bool isGameTied()\n    {\n      return !GameBoard.Any(spot => spot == Unplayed);\n    }\n\n    \n    static Random rnd = new Random();\n\n    static void initializeGameBoard()\n    {\n      for (int i = 0; i < GameBoard.Length; i++)\n        GameBoard[i] = Unplayed;\n    }\n\n    static string playerName(int player)\n    {\n      return Players[player][0];\n    }\n\n    static string playerToken(int player)\n    {\n      return Players[player][1];\n    }\n\n    static int getNextPlayer(int player)\n    {\n      return (player + 1) % 2;\n    }\n\n    static void displayGameBoard()\n    {\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(0), pieceAt(1), pieceAt(2));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(3), pieceAt(4), pieceAt(5));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(6), pieceAt(7), pieceAt(8));\n      Console.WriteLine();\n    }\n\n    static string pieceAt(int boardPosition)\n    {\n      if (GameBoard[boardPosition] == Unplayed)\n        return (boardPosition + 1).ToString();  \n      return playerToken(GameBoard[boardPosition]);\n    }\n\n    private static bool playAgain()\n    {\n      Console.WriteLine(\"\\nDo you want to play again?\");\n      return Console.ReadKey(false).Key == ConsoleKey.Y;\n    }\n  }\n\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n"}
{"id": 39175, "name": "Integer sequence", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 39176, "name": "Integer sequence", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 39177, "name": "DNS query", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 39178, "name": "Seven-sided dice from five-sided dice", "C#": "using System;\n\npublic class SevenSidedDice\n{\n    Random random = new Random();\n\t\t\n        static void Main(string[] args)\n\t\t{\n\t\t\tSevenSidedDice sevenDice = new SevenSidedDice();\n\t\t\tConsole.WriteLine(\"Random number from 1 to 7: \"+ sevenDice.seven());\n            Console.Read();\n\t\t}\n\t\t\n\t\tint seven()\n\t\t{\n\t\t\tint v=21;\n\t\t\twhile(v>20)\n\t\t\t\tv=five()+five()*5-6;\n\t\t\treturn 1+v%7;\n\t\t}\n\t\t\n\t\tint five()\n\t\t{\n        return 1 + random.Next(5);\n\t\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 39179, "name": "Magnanimous numbers", "C#": "using System; using static System.Console;\n\nclass Program {\n\n  static bool[] np; \n\n  static void ms(long lmt) { \n    np = new bool[lmt]; np[0] = np[1] = true;\n    for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])\n        for (long k = n * n; k < lmt; k += n) np[k] = true; }\n\n  static bool is_Mag(long n) { long res, rem;\n    for (long p = 10; n >= p; p *= 10) {\n      res = Math.DivRem (n, p, out rem);\n      if (np[res + rem]) return false; } return true; }\n\n  static void Main(string[] args) { ms(100_009); string mn;\n    WriteLine(\"First 45{0}\", mn = \" magnanimous numbers:\");\n    for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {\n      if (c++ < 45 || (c > 240 && c <= 250) || c > 390)\n        Write(c <= 45 ? \"{0,4} \" : \"{0,8:n0} \", l);\n      if (c < 45 && c % 15 == 0) WriteLine();\n      if (c == 240) WriteLine (\"\\n\\n241st through 250th{0}\", mn);\n      if (c == 390) WriteLine (\"\\n\\n391st through 400th{0}\", mn); } }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n"}
{"id": 39180, "name": "Create a two-dimensional array at runtime", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n"}
{"id": 39181, "name": "Create a two-dimensional array at runtime", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n"}
{"id": 39182, "name": "Chinese remainder theorem", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 39183, "name": "Chinese remainder theorem", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 39184, "name": "Chinese remainder theorem", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 39185, "name": "Pi", "C#": "using System;\nusing System.Numerics;\n\nnamespace PiCalc {\n    internal class Program {\n        private readonly BigInteger FOUR = new BigInteger(4);\n        private readonly BigInteger SEVEN = new BigInteger(7);\n        private readonly BigInteger TEN = new BigInteger(10);\n        private readonly BigInteger THREE = new BigInteger(3);\n        private readonly BigInteger TWO = new BigInteger(2);\n\n        private BigInteger k = BigInteger.One;\n        private BigInteger l = new BigInteger(3);\n        private BigInteger n = new BigInteger(3);\n        private BigInteger q = BigInteger.One;\n        private BigInteger r = BigInteger.Zero;\n        private BigInteger t = BigInteger.One;\n\n        public void CalcPiDigits() {\n            BigInteger nn, nr;\n            bool first = true;\n            while (true) {\n                if ((FOUR*q + r - t).CompareTo(n*t) == -1) {\n                    Console.Write(n);\n                    if (first) {\n                        Console.Write(\".\");\n                        first = false;\n                    }\n                    nr = TEN*(r - (n*t));\n                    n = TEN*(THREE*q + r)/t - (TEN*n);\n                    q *= TEN;\n                    r = nr;\n                } else {\n                    nr = (TWO*q + r)*l;\n                    nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);\n                    q *= k;\n                    t *= l;\n                    l += TWO;\n                    k += BigInteger.One;\n                    n = nn;\n                    r = nr;\n                }\n            }\n        }\n\n        private static void Main(string[] args) {\n            new Program().CalcPiDigits();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n"}
{"id": 39186, "name": "Y combinator", "C#": "using System;\n\nstatic class YCombinator<T, TResult>\n{\n    \n    private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);\n\n    public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =\n        f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));\n}\n\nstatic class Program\n{\n    static void Main()\n    {\n        var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));\n        var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));\n\n        Console.WriteLine(fac(10));\n        Console.WriteLine(fib(10));\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n"}
{"id": 39187, "name": "Van Eck sequence", "C#": "using System.Linq; class Program { static void Main() {\n    int a, b, c, d, e, f, g; int[] h = new int[g = 1000];\n    for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)\n        for (d = a, e = b - d, f = h[b]; e <= b; e++)\n            if (f == h[d--]) { h[c] = e; break; }\n    void sho(int i) { System.Console.WriteLine(string.Join(\" \",\n        h.Skip(i).Take(10))); } sho(0); sho(990); } }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 39188, "name": "Van Eck sequence", "C#": "using System.Linq; class Program { static void Main() {\n    int a, b, c, d, e, f, g; int[] h = new int[g = 1000];\n    for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)\n        for (d = a, e = b - d, f = h[b]; e <= b; e++)\n            if (f == h[d--]) { h[c] = e; break; }\n    void sho(int i) { System.Console.WriteLine(string.Join(\" \",\n        h.Skip(i).Take(10))); } sho(0); sho(990); } }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 39189, "name": "Bitwise operations", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 39190, "name": "Dragon curve", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n"}
{"id": 39191, "name": "Read a file line by line", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 39192, "name": "Doubly-linked list_Element insertion", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n"}
{"id": 39193, "name": "Smarandache prime-digital sequence", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n"}
{"id": 39194, "name": "Quickselect algorithm", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n"}
{"id": 39195, "name": "Non-decimal radices_Convert", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n", "Python": "i = int('1a',16)  \n"}
{"id": 39196, "name": "Walk a directory_Recursively", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 39197, "name": "Main step of GOST 28147-89", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n"}
{"id": 39198, "name": "Main step of GOST 28147-89", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n"}
{"id": 39199, "name": "State name puzzle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n"}
{"id": 39200, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 39201, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 39202, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 39203, "name": "Classes", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 39204, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 39205, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 39206, "name": "LZW compression", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 39207, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 39208, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 39209, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 39210, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 39211, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 39212, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 39213, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 39214, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 39215, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 39216, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 39217, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 39218, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 39219, "name": "Mertens function", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n"}
{"id": 39220, "name": "Order by pair comparisons", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n"}
{"id": 39221, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 39222, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 39223, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 39224, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 39225, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 39226, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 39227, "name": "Snake", "C": "\n\n\n\n\n\n\n\n\nchar nonblocking_getch();\nvoid positional_putch(int x, int y, char ch);\nvoid millisecond_sleep(int n);\nvoid init_screen();\nvoid update_screen();\nvoid close_screen();\n\n\n\n#ifdef __linux__\n#define _POSIX_C_SOURCE 200809L\n#include <time.h> \n#include <ncurses.h> \nchar nonblocking_getch() { return getch(); }\nvoid positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }\nvoid millisecond_sleep(int n) { \n\tstruct timespec t = { 0, n * 1000000 };\n\tnanosleep(&t, 0);\n\t\n}\nvoid update_screen() { refresh(); }\nvoid init_screen() {\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\tnodelay(stdscr, TRUE);\n}\nvoid close_screen() { endwin(); }\n#endif\n\n\n#ifdef _WIN32\n#error \"not implemented\"\n#endif\n\n\n#include <time.h> \n#include <stdlib.h> \n\n#define w 80\n#define h 40\n\nint board[w * h];\nint head;\nenum Dir { N, E, S, W } dir;\nint quit;\n\nenum State { SPACE=0, FOOD=1, BORDER=2 };\n\n\n\nvoid age() {\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tif(board[i] < 0)\n\t\t\t++board[i];\n}\n\n\nvoid plant() {\n\tint r;\n\tdo\n\t\tr = rand() % (w * h);\n\twhile(board[r] != SPACE);\n\tboard[r] = FOOD;\n}\n\n\nvoid start(void) {\n        int i;\n\tfor(i = 0; i < w; ++i)\n\t\tboard[i] = board[i + (h - 1) * w] = BORDER;\n\tfor(i = 0; i < h; ++i)\n\t\tboard[i * w] = board[i * w + w - 1] = BORDER;\n\thead = w * (h - 1 - h % 2) / 2; \n\tboard[head] = -5;\n\tdir = N;\n\tquit = 0;\n\tsrand(time(0));\n\tplant();\n}\n\nvoid step() {\n\tint len = board[head];\n\tswitch(dir) {\n\t\tcase N: head -= w; break;\n\t\tcase S: head += w; break;\n\t\tcase W: --head; break;\n\t\tcase E: ++head; break;\n\t}\n\tswitch(board[head]) {\n\t\tcase SPACE:\n\t\t\tboard[head] = len - 1; \n\t\t\tage();\n\t\t\tbreak;\n\t\tcase FOOD:\n\t\t\tboard[head] = len - 1;\n\t\t\tplant();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tquit = 1;\n\t}\n}\n\nvoid show() {\n\tconst char * symbol = \" @.\";\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tpositional_putch(i / w, i % w,\n\t\t\tboard[i] < 0 ? '#' : symbol[board[i]]);\n\tupdate_screen();\n}\n\nint main (int argc, char * argv[]) {\n\tinit_screen();\n\tstart();\n\tdo {\n\t\tshow();\n\t\tswitch(nonblocking_getch()) {\n\t\t\tcase 'i': dir = N; break;\n\t\t\tcase 'j': dir = W; break;\n\t\t\tcase 'k': dir = S; break;\n\t\t\tcase 'l': dir = E; break;\n\t\t\tcase 'q': quit = 1; break;\n\t\t}\n\t\tstep();\n\t\tmillisecond_sleep(100); \n\t\t\n\t}\n\twhile(!quit);\n\tmillisecond_sleep(999);\n\tclose_screen();\n\treturn 0;\n}\n", "Python": "from __future__ import annotations\n\nimport itertools\nimport random\n\nfrom enum import Enum\n\nfrom typing import Any\nfrom typing import Tuple\n\nimport pygame as pg\n\nfrom pygame import Color\nfrom pygame import Rect\n\nfrom pygame.surface import Surface\n\nfrom pygame.sprite import AbstractGroup\nfrom pygame.sprite import Group\nfrom pygame.sprite import RenderUpdates\nfrom pygame.sprite import Sprite\n\n\nclass Direction(Enum):\n    UP = (0, -1)\n    DOWN = (0, 1)\n    LEFT = (-1, 0)\n    RIGHT = (1, 0)\n\n    def opposite(self, other: Direction):\n        return (self[0] + other[0], self[1] + other[1]) == (0, 0)\n\n    def __getitem__(self, i: int):\n        return self.value[i]\n\n\nclass SnakeHead(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        facing: Direction,\n        bounds: Rect,\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"aquamarine4\"))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n        self.facing = facing\n        self.size = size\n        self.speed = size\n        self.bounds = bounds\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        \n        self.rect.move_ip(\n            (\n                self.facing[0] * self.speed,\n                self.facing[1] * self.speed,\n            )\n        )\n\n        \n        if self.rect.right > self.bounds.right:\n            self.rect.left = 0\n        elif self.rect.left < 0:\n            self.rect.right = self.bounds.right\n\n        if self.rect.bottom > self.bounds.bottom:\n            self.rect.top = 0\n        elif self.rect.top < 0:\n            self.rect.bottom = self.bounds.bottom\n\n    def change_direction(self, direction: Direction):\n        if not self.facing == direction and not direction.opposite(self.facing):\n            self.facing = direction\n\n\nclass SnakeBody(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        colour: str = \"white\",\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(colour))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n\n\nclass Snake(RenderUpdates):\n    def __init__(self, game: Game) -> None:\n        self.segment_size = game.segment_size\n        self.colours = itertools.cycle([\"aquamarine1\", \"aquamarine3\"])\n\n        self.head = SnakeHead(\n            size=self.segment_size,\n            position=game.rect.center,\n            facing=Direction.RIGHT,\n            bounds=game.rect,\n        )\n\n        neck = [\n            SnakeBody(\n                size=self.segment_size,\n                position=game.rect.center,\n                colour=next(self.colours),\n            )\n            for _ in range(2)\n        ]\n\n        super().__init__(*[self.head, *neck])\n\n        self.body = Group()\n        self.tail = neck[-1]\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        self.head.update()\n\n        \n        segments = self.sprites()\n        for i in range(len(segments) - 1, 0, -1):\n            \n            segments[i].rect.center = segments[i - 1].rect.center\n\n    def change_direction(self, direction: Direction):\n        self.head.change_direction(direction)\n\n    def grow(self):\n        tail = SnakeBody(\n            size=self.segment_size,\n            position=self.tail.rect.center,\n            colour=next(self.colours),\n        )\n        self.tail = tail\n        self.add(self.tail)\n        self.body.add(self.tail)\n\n\nclass SnakeFood(Sprite):\n    def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None:\n        super().__init__(*groups)\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"red\"))\n        self.rect = self.image.get_rect()\n\n        self.rect.topleft = (\n            random.randint(0, game.rect.width),\n            random.randint(0, game.rect.height),\n        )\n\n        self.rect.clamp_ip(game.rect)\n\n        \n        \n        while pg.sprite.spritecollideany(self, game.snake):\n            self.rect.topleft = (\n                random.randint(0, game.rect.width),\n                random.randint(0, game.rect.height),\n            )\n\n            self.rect.clamp_ip(game.rect)\n\n\nclass Game:\n    def __init__(self) -> None:\n        self.rect = Rect(0, 0, 640, 480)\n        self.background = Surface(self.rect.size)\n        self.background.fill(Color(\"black\"))\n\n        self.score = 0\n        self.framerate = 16\n\n        self.segment_size = 10\n        self.snake = Snake(self)\n        self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size))\n\n        pg.init()\n\n    def _init_display(self) -> Surface:\n        bestdepth = pg.display.mode_ok(self.rect.size, 0, 32)\n        screen = pg.display.set_mode(self.rect.size, 0, bestdepth)\n\n        pg.display.set_caption(\"Snake\")\n        pg.mouse.set_visible(False)\n\n        screen.blit(self.background, (0, 0))\n        pg.display.flip()\n\n        return screen\n\n    def draw(self, screen: Surface):\n        dirty = self.snake.draw(screen)\n        pg.display.update(dirty)\n\n        dirty = self.food_group.draw(screen)\n        pg.display.update(dirty)\n\n    def update(self, screen):\n        self.food_group.clear(screen, self.background)\n        self.food_group.update()\n        self.snake.clear(screen, self.background)\n        self.snake.update()\n\n    def main(self) -> int:\n        screen = self._init_display()\n        clock = pg.time.Clock()\n\n        while self.snake.head.alive():\n            for event in pg.event.get():\n                if event.type == pg.QUIT or (\n                    event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q)\n                ):\n                    return self.score\n\n            \n            keystate = pg.key.get_pressed()\n\n            if keystate[pg.K_RIGHT]:\n                self.snake.change_direction(Direction.RIGHT)\n            elif keystate[pg.K_LEFT]:\n                self.snake.change_direction(Direction.LEFT)\n            elif keystate[pg.K_UP]:\n                self.snake.change_direction(Direction.UP)\n            elif keystate[pg.K_DOWN]:\n                self.snake.change_direction(Direction.DOWN)\n\n            \n            self.update(screen)\n\n            \n            for food in pg.sprite.spritecollide(\n                self.snake.head, self.food_group, dokill=False\n            ):\n                food.kill()\n                self.snake.grow()\n                self.score += 1\n\n                \n                if self.score % 5 == 0:\n                    self.framerate += 1\n\n                self.food_group.add(SnakeFood(self, self.segment_size))\n\n            \n            if pg.sprite.spritecollideany(self.snake.head, self.snake.body):\n                self.snake.head.kill()\n\n            self.draw(screen)\n            clock.tick(self.framerate)\n\n        return self.score\n\n\nif __name__ == \"__main__\":\n    game = Game()\n    score = game.main()\n    print(score)\n"}
{"id": 39228, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 39229, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 39230, "name": "Legendre prime counting function", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n"}
{"id": 39231, "name": "Use another language to call a function", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n"}
{"id": 39232, "name": "Longest string challenge", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 39233, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 39234, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 39235, "name": "Create a file", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 39236, "name": "Unprimeable numbers", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n"}
{"id": 39237, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 39238, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 39239, "name": "Chernick's Carmichael numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n"}
{"id": 39240, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 39241, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 39242, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 39243, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 39244, "name": "Sequence of primorial primes", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n"}
{"id": 39245, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 39246, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 39247, "name": "Dining philosophers", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n"}
{"id": 39248, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 39249, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 39250, "name": "Logistic curve fitting in epidemiology", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n"}
{"id": 39251, "name": "Sorting algorithms_Strand sort", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n"}
{"id": 39252, "name": "Additive primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 39253, "name": "Inverted syntax", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n", "Python": "x = truevalue if condition else falsevalue\n"}
{"id": 39254, "name": "Inverted syntax", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n", "Python": "x = truevalue if condition else falsevalue\n"}
{"id": 39255, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 39256, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 39257, "name": "Delegates", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 39258, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 39259, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 39260, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39261, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39262, "name": "Enforced immutability", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 39263, "name": "Sutherland-Hodgman polygon clipping", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n"}
{"id": 39264, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 39265, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 39266, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n"}
{"id": 39267, "name": "Optional parameters", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n"}
{"id": 39268, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 39269, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 39270, "name": "Call a foreign-language function", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 39271, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 39272, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 39273, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 39274, "name": "Faulhaber's triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 39275, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 39276, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 39277, "name": "Word wheel", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n"}
{"id": 39278, "name": "Array concatenation", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 39279, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 39280, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 39281, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 39282, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 39283, "name": "Primes - allocate descendants to their ancestors", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n"}
{"id": 39284, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 39285, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 39286, "name": "First-class functions", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 39287, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 39288, "name": "XML_Output", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n"}
{"id": 39289, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 39290, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 39291, "name": "Regular expressions", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 39292, "name": "Guess the number_With feedback (player)", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n"}
{"id": 39293, "name": "Hash from two arrays", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 39294, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 39295, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 39296, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 39297, "name": "Fractal tree", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n"}
{"id": 39298, "name": "Colour pinstripe_Display", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n"}
{"id": 39299, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 39300, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 39301, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n"}
{"id": 39302, "name": "Animate a pendulum", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n"}
{"id": 39303, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 39304, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 39305, "name": "Create a file on magnetic tape", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n"}
{"id": 39306, "name": "Sorting algorithms_Heapsort", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n"}
{"id": 39307, "name": "Playing cards", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 39308, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 39309, "name": "Sierpinski carpet", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 39310, "name": "Sorting algorithms_Bogosort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 39311, "name": "Merge and aggregate datasets", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n"}
{"id": 39312, "name": "Euler method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n"}
{"id": 39313, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 39314, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 39315, "name": "JortSort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n"}
{"id": 39316, "name": "Leap year", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 39317, "name": "Combinations and permutations", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n"}
{"id": 39318, "name": "Sort numbers lexicographically", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n"}
{"id": 39319, "name": "Number names", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 39320, "name": "Compare length of two strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 39321, "name": "Sorting algorithms_Shell sort", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 39322, "name": "Doubly-linked list_Definition", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n"}
{"id": 39323, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 39324, "name": "Permutation test", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n"}
{"id": 39325, "name": "Möbius function", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n"}
{"id": 39326, "name": "Increment a numerical string", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n", "Python": "next = str(int('123') + 1)\n"}
{"id": 39327, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 39328, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 39329, "name": "Sorting algorithms_Permutation sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n"}
{"id": 39330, "name": "Averages_Arithmetic mean", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 39331, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39332, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39333, "name": "Entropy", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 39334, "name": "Tokenize a string with escaping", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n"}
{"id": 39335, "name": "Sexy primes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef unsigned char bool;\n\nvoid sieve(bool *c, int limit) {\n    int i, p = 3, p2;\n    \n    c[0] = TRUE;\n    c[1] = TRUE;\n    \n    for (;;) {\n        p2 = p * p;\n        if (p2 >= limit) {\n            break;\n        }\n        for (i = p2; i < limit; i += 2*p) {\n            c[i] = TRUE;\n        }\n        for (;;) {\n            p += 2;\n            if (!c[p]) {\n                break;\n            }\n        }\n    }\n}\n\nvoid printHelper(const char *cat, int len, int lim, int n) {\n    const char *sp = strcmp(cat, \"unsexy primes\") ? \"sexy prime \" : \"\";\n    const char *verb = (len == 1) ? \"is\" : \"are\";\n    printf(\"Number of %s%s less than %'d = %'d\\n\", sp, cat, lim, len);\n    printf(\"The last %d %s:\\n\", n, verb);\n}\n\nvoid printArray(int *a, int len) {\n    int i;\n    printf(\"[\");\n    for (i = 0; i < len; ++i) printf(\"%d \", a[i]);\n    printf(\"\\b]\");\n}\n\nint main() {\n    int i, ix, n, lim = 1000035;\n    int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;\n    int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;\n    int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;\n    int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];\n    int last_un[10];\n    bool *sv = calloc(lim - 1, sizeof(bool)); \n    setlocale(LC_NUMERIC, \"\");\n    sieve(sv, lim);\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            unsexy++;\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pairs++;\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            trips++;\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            quads++;\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            quins++;\n        }\n    }\n    if (pairs < lpr) lpr = pairs;\n    if (trips < ltr) ltr = trips;\n    if (quads < lqd) lqd = quads;\n    if (quins < lqn) lqn = quins;\n    if (unsexy < lun) lun = unsexy;\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            un++;\n            if (un > unsexy - lun) {\n                last_un[un + lun - 1 - unsexy] = i;\n            }\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pr++;\n            if (pr > pairs - lpr) {\n                ix = pr + lpr - 1 - pairs;\n                last_pr[ix][0] = i; last_pr[ix][1] = i + 6;\n            }\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            tr++;\n            if (tr > trips - ltr) {\n                ix = tr + ltr - 1 - trips;\n                last_tr[ix][0] = i; last_tr[ix][1] = i + 6;\n                last_tr[ix][2] = i + 12;\n            }\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            qd++;\n            if (qd > quads - lqd) {\n                ix = qd + lqd - 1 - quads;\n                last_qd[ix][0] = i; last_qd[ix][1] = i + 6;\n                last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;\n            }\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            qn++;\n            if (qn > quins - lqn) {\n                ix = qn + lqn - 1 - quins;\n                last_qn[ix][0] = i; last_qn[ix][1] = i + 6;\n                last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;\n                last_qn[ix][4] = i + 24;\n            }\n        }\n    }\n\n    printHelper(\"pairs\", pairs, lim, lpr);\n    printf(\"  [\");\n    for (i = 0; i < lpr; ++i) {\n        printArray(last_pr[i], 2);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"triplets\", trips, lim, ltr);\n    printf(\"  [\");\n    for (i = 0; i < ltr; ++i) {\n        printArray(last_tr[i], 3);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quadruplets\", quads, lim, lqd);\n    printf(\"  [\");\n    for (i = 0; i < lqd; ++i) {\n        printArray(last_qd[i], 4);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quintuplets\", quins, lim, lqn);\n    printf(\"  [\");\n    for (i = 0; i < lqn; ++i) {\n        printArray(last_qn[i], 5);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"unsexy primes\", unsexy, lim, lun);\n    printf(\"  [\");\n    printArray(last_un, lun);\n    printf(\"\\b]\\n\");\n    free(sv);\n    return 0;\n}\n", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n"}
{"id": 39336, "name": "Forward difference", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 39337, "name": "Primality by trial division", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 39338, "name": "Evaluate binomial coefficients", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 39339, "name": "Evaluate binomial coefficients", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 39340, "name": "Collections", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 39341, "name": "Singly-linked list_Traversal", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n", "Python": "for node in lst:\n    print node.value\n"}
{"id": 39342, "name": "Bitmap_Write a PPM file", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 39343, "name": "Delete a file", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 39344, "name": "Delete a file", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 39345, "name": "Discordian date", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 39346, "name": "Flipping bits game", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 39347, "name": "Flipping bits game", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 39348, "name": "Hickerson series of almost integers", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 39349, "name": "Hickerson series of almost integers", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 39350, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 39351, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 39352, "name": "String interpolation (included)", "C": "#include <stdio.h>\n\nint main() {\n  const char *extra = \"little\";\n  printf(\"Mary had a %s lamb.\\n\", extra);\n  return 0;\n}\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 39353, "name": "Sorting algorithms_Patience sort", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint* patienceSort(int* arr,int size){\n\tint decks[size][size],i,j,min,pickedRow;\n\t\n\tint *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){\n\t\t\t\tdecks[j][count[j]] = arr[i];\n\t\t\t\tcount[j]++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmin = decks[0][count[0]-1];\n\tpickedRow = 0;\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]>0 && decks[j][count[j]-1]<min){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t}\n\t\t}\n\t\tsortedArr[i] = min;\n\t\tcount[pickedRow]--;\n\t\t\n\t\tfor(j=0;j<size;j++)\n\t\t\tif(count[j]>0){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\t\n\tfree(count);\n\tfree(decks);\n\t\n\treturn sortedArr;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr, *sortedArr, i;\n\t\n\tif(argC==0)\n\t\tprintf(\"Usage : %s <integers to be sorted separated by space>\");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i<=argC;i++)\n\t\t\tarr[i-1] = atoi(argV[i]);\n\t\t\n\t\tsortedArr = patienceSort(arr,argC-1);\n\t\t\n\t\tfor(i=0;i<argC-1;i++)\n\t\t\tprintf(\"%d \",sortedArr[i]);\n\t}\n\t\n\treturn 0;\n}\n", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n"}
{"id": 39354, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 39355, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 39356, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 39357, "name": "Tau number", "C": "#include <stdio.h>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    unsigned int p;\n\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int count = 0;\n    unsigned int n;\n\n    printf(\"The first %d tau numbers are:\\n\", limit);\n    for (n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            printf(\"%6d\", n);\n            ++count;\n            if (count % 10 == 0) {\n                printf(\"\\n\");\n            }\n        }\n    }\n\n    return 0;\n}\n", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n"}
{"id": 39358, "name": "Determinant and permanent", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 39359, "name": "Determinant and permanent", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 39360, "name": "Partition function P", "C": "#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <gmp.h>\n\nmpz_t* partition(uint64_t n) {\n\tmpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));\n\tmpz_init_set_ui(pn[0], 1);\n\tmpz_init_set_ui(pn[1], 1);\n\tfor (uint64_t i = 2; i < n + 2; i ++) {\n\t\tmpz_init(pn[i]);\n\t\tfor (uint64_t k = 1, penta; ; k++) {\n\t\t\tpenta = k * (3 * k - 1) >> 1;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t\tpenta += k;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t}\n\t}\n\tmpz_t *tmp = &pn[n + 1];\n\tfor (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);\n\tfree(pn);\n\treturn tmp;\n}\n\nint main(int argc, char const *argv[]) {\n\tclock_t start = clock();\n\tmpz_t *p = partition(6666);\n\tgmp_printf(\"%Zd\\n\", p);\n\tprintf(\"Elapsed time: %.04f seconds\\n\",\n\t\t(double)(clock() - start) / (double)CLOCKS_PER_SEC);\n\treturn 0;\n}\n", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n"}
{"id": 39361, "name": "Wireworld", "C": "\n#define ANIMATE_VT100_POSIX\n#include <stdio.h>\n#include <string.h>\n#ifdef ANIMATE_VT100_POSIX\n#include <time.h>\n#endif\n\nchar world_7x14[2][512] = {\n  {\n    \"+-----------+\\n\"\n    \"|tH.........|\\n\"\n    \"|.   .      |\\n\"\n    \"|   ...     |\\n\"\n    \"|.   .      |\\n\"\n    \"|Ht.. ......|\\n\"\n    \"+-----------+\\n\"\n  }\n};\n\nvoid next_world(const char *in, char *out, int w, int h)\n{\n  int i;\n\n  for (i = 0; i < w*h; i++) {\n    switch (in[i]) {\n    case ' ': out[i] = ' '; break;\n    case 't': out[i] = '.'; break;\n    case 'H': out[i] = 't'; break;\n    case '.': {\n      int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') +\n               (in[i-1]   == 'H')                    + (in[i+1]   == 'H') +\n               (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H');\n      out[i] = (hc == 1 || hc == 2) ? 'H' : '.';\n      break;\n    }\n    default:\n      out[i] = in[i];\n    }\n  }\n  out[i] = in[i];\n}\n\nint main()\n{\n  int f;\n\n  for (f = 0; ; f = 1 - f) {\n    puts(world_7x14[f]);\n    next_world(world_7x14[f], world_7x14[1-f], 14, 7);\n#ifdef ANIMATE_VT100_POSIX\n    printf(\"\\x1b[%dA\", 8);\n    printf(\"\\x1b[%dD\", 14);\n    {\n      static const struct timespec ts = { 0, 100000000 };\n      nanosleep(&ts, 0);\n    }\n#endif\n  }\n\n  return 0;\n}\n", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n"}
{"id": 39362, "name": "Ray-casting algorithm", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec;\ntypedef struct { int n; vec* v; } polygon_t, *polygon;\n\n#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}\n#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }\nBIN_V(sub, a.x - b.x, a.y - b.y);\nBIN_V(add, a.x + b.x, a.y + b.y);\nBIN_S(dot, a.x * b.x + a.y * b.y);\nBIN_S(cross, a.x * b.y - a.y * b.x);\n\n\nvec vmadd(vec a, double s, vec b)\n{\n\tvec c;\n\tc.x = a.x + s * b.x;\n\tc.y = a.y + s * b.y;\n\treturn c;\n}\n\n\nint intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)\n{\n\tvec dx = vsub(x1, x0), dy = vsub(y1, y0);\n\tdouble d = vcross(dy, dx), a;\n\tif (!d) return 0; \n\n\ta = (vcross(x0, dx) - vcross(y0, dx)) / d;\n\tif (sect)\n\t\t*sect = vmadd(y0, a, dy);\n\n\tif (a < -tol || a > 1 + tol) return -1;\n\tif (a < tol || a > 1 - tol) return 0;\n\n\ta = (vcross(x0, dy) - vcross(y0, dy)) / d;\n\tif (a < 0 || a > 1) return -1;\n\n\treturn 1;\n}\n\n\ndouble dist(vec x, vec y0, vec y1, double tol)\n{\n\tvec dy = vsub(y1, y0);\n\tvec x1, s;\n\tint r;\n\n\tx1.x = x.x + dy.y; x1.y = x.y - dy.x;\n\tr = intersect(x, x1, y0, y1, tol, &s);\n\tif (r == -1) return HUGE_VAL;\n\ts = vsub(s, x);\n\treturn sqrt(vdot(s, s));\n}\n\n#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)\n\nint inside(vec v, polygon p, double tol)\n{\n\t\n\tint i, k, crosses, intersectResult;\n\tvec *pv;\n\tdouble min_x, max_x, min_y, max_y;\n\n\tfor (i = 0; i < p->n; i++) {\n\t\tk = (i + 1) % p->n;\n\t\tmin_x = dist(v, p->v[i], p->v[k], tol);\n\t\tif (min_x < tol) return 0;\n\t}\n\n\tmin_x = max_x = p->v[0].x;\n\tmin_y = max_y = p->v[1].y;\n\n\t\n\tfor_v(i, pv, p) {\n\t\tif (pv->x > max_x) max_x = pv->x;\n\t\tif (pv->x < min_x) min_x = pv->x;\n\t\tif (pv->y > max_y) max_y = pv->y;\n\t\tif (pv->y < min_y) min_y = pv->y;\n\t}\n\tif (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)\n\t\treturn -1;\n\n\tmax_x -= min_x; max_x *= 2;\n\tmax_y -= min_y; max_y *= 2;\n\tmax_x += max_y;\n\n\tvec e;\n\twhile (1) {\n\t\tcrosses = 0;\n\t\t\n\t\te.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\t\te.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\n\t\tfor (i = 0; i < p->n; i++) {\n\t\t\tk = (i + 1) % p->n;\n\t\t\tintersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);\n\n\t\t\t\n\t\t\tif (!intersectResult) break;\n\n\t\t\tif (intersectResult == 1) crosses++;\n\t\t}\n\t\tif (i == p->n) break;\n\t}\n\treturn (crosses & 1) ? 1 : -1;\n}\n\nint main()\n{\n\tvec vsq[] = {\t{0,0}, {10,0}, {10,10}, {0,10},\n\t\t\t{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};\n\n\tpolygon_t sq = { 4, vsq }, \n\t\tsq_hole = { 8, vsq }; \n\n\tvec c = { 10, 5 }; \n\tvec d = { 5, 5 };\n\n\tprintf(\"%d\\n\", inside(c, &sq, 1e-10));\n\tprintf(\"%d\\n\", inside(c, &sq_hole, 1e-10));\n\n\tprintf(\"%d\\n\", inside(d, &sq, 1e-10));\t\n\tprintf(\"%d\\n\", inside(d, &sq_hole, 1e-10));  \n\n\treturn 0;\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 39363, "name": "Elliptic curve arithmetic", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 39364, "name": "Elliptic curve arithmetic", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 39365, "name": "Count occurrences of a substring", "C": "#include <stdio.h>\n#include <string.h>\n\nint match(const char *s, const char *p, int overlap)\n{\n        int c = 0, l = strlen(p);\n\n        while (*s != '\\0') {\n                if (strncmp(s++, p, l)) continue;\n                if (!overlap) s += l - 1;\n                c++;\n        }\n        return c;\n}\n\nint main()\n{\n        printf(\"%d\\n\", match(\"the three truths\", \"th\", 0));\n        printf(\"overlap:%d\\n\", match(\"abababababa\", \"aba\", 1));\n        printf(\"not:    %d\\n\", match(\"abababababa\", \"aba\", 0));\n        return 0;\n}\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 39366, "name": "Numbers with prime digits whose sum is 13", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 39367, "name": "Numbers with prime digits whose sum is 13", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 39368, "name": "Numbers with prime digits whose sum is 13", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 39369, "name": "String comparison", "C": "\nif (strcmp(a,b)) action_on_equality();\n", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n"}
{"id": 39370, "name": "Take notes on the command line", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 39371, "name": "Take notes on the command line", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 39372, "name": "Thiele's interpolation formula", "C": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define N 32\n#define N2 (N * (N - 1) / 2)\n#define STEP .05\n\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\n\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\n\n\n\ndouble rho(double *x, double *y, double *r, int i, int n)\n{\n\tif (n < 0) return 0;\n\tif (!n) return y[i];\n\n\tint idx = (N - 1 - n) * (N - n) / 2 + i;\n\tif (r[idx] != r[idx]) \n\t\tr[idx] = (x[i] - x[i + n])\n\t\t\t/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n\t\t\t+ rho(x, y, r, i + 1, n - 2);\n\treturn r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, int n)\n{\n\tif (n > N - 1) return 1;\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n\t\t+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\n#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)\n#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)\n#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\txval[i] = i * STEP;\n\t\tt_sin[i] = sin(xval[i]);\n\t\tt_cos[i] = cos(xval[i]);\n\t\tt_tan[i] = t_sin[i] / t_cos[i];\n\t}\n\tfor (i = 0; i < N2; i++)\n\t\t\n\t\tr_sin[i] = r_cos[i] = r_tan[i] = 0/0.;\n\n\tprintf(\"%16.14f\\n\", 6 * i_sin(.5));\n\tprintf(\"%16.14f\\n\", 3 * i_cos(.5));\n\tprintf(\"%16.14f\\n\", 4 * i_tan(1.));\n\treturn 0;\n}\n", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n"}
{"id": 39373, "name": "Fibonacci word", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 39374, "name": "Fibonacci word", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 39375, "name": "Angles (geometric), normalization and conversion", "C": "#define PI 3.141592653589793\n#define TWO_PI 6.283185307179586\n\ndouble normalize2deg(double a) {\n  while (a < 0) a += 360;\n  while (a >= 360) a -= 360;\n  return a;\n}\ndouble normalize2grad(double a) {\n  while (a < 0) a += 400;\n  while (a >= 400) a -= 400;\n  return a;\n}\ndouble normalize2mil(double a) {\n  while (a < 0) a += 6400;\n  while (a >= 6400) a -= 6400;\n  return a;\n}\ndouble normalize2rad(double a) {\n  while (a < 0) a += TWO_PI;\n  while (a >= TWO_PI) a -= TWO_PI;\n  return a;\n}\n\ndouble deg2grad(double a) {return a * 10 / 9;}\ndouble deg2mil(double a) {return a * 160 / 9;}\ndouble deg2rad(double a) {return a * PI / 180;}\n\ndouble grad2deg(double a) {return a * 9 / 10;}\ndouble grad2mil(double a) {return a * 16;}\ndouble grad2rad(double a) {return a * PI / 200;}\n\ndouble mil2deg(double a) {return a * 9 / 160;}\ndouble mil2grad(double a) {return a / 16;}\ndouble mil2rad(double a) {return a * PI / 3200;}\n\ndouble rad2deg(double a) {return a * 180 / PI;}\ndouble rad2grad(double a) {return a * 200 / PI;}\ndouble rad2mil(double a) {return a * 3200 / PI;}\n", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n"}
{"id": 39376, "name": "Find common directory path", "C": "#include <stdio.h>\n\nint common_len(const char *const *names, int n, char sep)\n{\n\tint i, pos;\n\tfor (pos = 0; ; pos++) {\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tif (names[i][pos] != '\\0' &&\n\t\t\t\t\tnames[i][pos] == names[0][pos])\n\t\t\t\tcontinue;\n\n\t\t\t\n\t\t\twhile (pos > 0 && names[0][--pos] != sep);\n\t\t\treturn pos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint main()\n{\n\tconst char *names[] = {\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t};\n\tint len = common_len(names, sizeof(names) / sizeof(const char*), '/');\n\n\tif (!len) printf(\"No common path\\n\");\n\telse      printf(\"Common path: %.*s\\n\", len, names[0]);\n\n\treturn 0;\n}\n", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n"}
{"id": 39377, "name": "Verify distribution uniformity_Naive", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\ninline int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n\ninline int rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\n\nint check(int (*gen)(), int n, int cnt, double delta) \n{\n\tint i = cnt, *bins = calloc(sizeof(int), n);\n\tdouble ratio;\n\twhile (i--) bins[gen() - 1]++;\n\tfor (i = 0; i < n; i++) {\n\t\tratio = bins[i] * n / (double)cnt - 1;\n\t\tif (ratio > -delta && ratio < delta) continue;\n\n\t\tprintf(\"bin %d out of range: %d (%g%% vs %g%%), \",\n\t\t\ti + 1, bins[i], ratio * 100, delta * 100);\n\t\tbreak;\n\t}\n\tfree(bins);\n\treturn i == n;\n}\n\nint main()\n{\n\tint cnt = 1;\n\twhile ((cnt *= 10) <= 1000000) {\n\t\tprintf(\"Count = %d: \", cnt);\n\t\tprintf(check(rand5_7, 7, cnt, 0.03) ? \"flat\\n\" : \"NOT flat\\n\");\n\t}\n\n\treturn 0;\n}\n", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n"}
{"id": 39378, "name": "Stirling numbers of the second kind", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 39379, "name": "Stirling numbers of the second kind", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 39380, "name": "Recaman's sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 39381, "name": "Recaman's sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 39382, "name": "Memory allocation", "C": "#include <stdlib.h>\n\n\n#define SIZEOF_MEMB (sizeof(int))\n#define NMEMB 100\n\nint main()\n{\n  int *ints = malloc(SIZEOF_MEMB*NMEMB);\n  \n  ints = realloc(ints, sizeof(int)*(NMEMB+1));\n  \n  int *int2 = calloc(NMEMB, SIZEOF_MEMB);\n  \n  free(ints); free(int2);\n  return 0;\n}\n", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n"}
{"id": 39383, "name": "Tic-tac-toe", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint b[3][3]; \n\nint check_winner()\n{\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tif (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])\n\t\t\treturn b[i][0];\n\t\tif (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])\n\t\t\treturn b[0][i];\n\t}\n\tif (!b[1][1]) return 0;\n\n\tif (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];\n\tif (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];\n\n\treturn 0;\n}\n\nvoid showboard()\n{\n\tconst char *t = \"X O\";\n\tint i, j;\n\tfor (i = 0; i < 3; i++, putchar('\\n'))\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%c \", t[ b[i][j] + 1 ]);\n\tprintf(\"-----\\n\");\n}\n\n#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)\nint best_i, best_j;\nint test_move(int val, int depth)\n{\n\tint i, j, score;\n\tint best = -1, changed = 0;\n\n\tif ((score = check_winner())) return (score == val) ? 1 : -1;\n\n\tfor_ij {\n\t\tif (b[i][j]) continue;\n\n\t\tchanged = b[i][j] = val;\n\t\tscore = -test_move(-val, depth + 1);\n\t\tb[i][j] = 0;\n\n\t\tif (score <= best) continue;\n\t\tif (!depth) {\n\t\t\tbest_i = i;\n\t\t\tbest_j = j;\n\t\t}\n\t\tbest = score;\n\t}\n\n\treturn changed ? best : 0;\n}\n\nconst char* game(int user)\n{\n\tint i, j, k, move, win = 0;\n\tfor_ij b[i][j] = 0;\n\n\tprintf(\"Board postions are numbered so:\\n1 2 3\\n4 5 6\\n7 8 9\\n\");\n\tprintf(\"You have O, I have X.\\n\\n\");\n\tfor (k = 0; k < 9; k++, user = !user) {\n\t\twhile(user) {\n\t\t\tprintf(\"your move: \");\n\t\t\tif (!scanf(\"%d\", &move)) {\n\t\t\t\tscanf(\"%*s\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (--move < 0 || move >= 9) continue;\n\t\t\tif (b[i = move / 3][j = move % 3]) continue;\n\n\t\t\tb[i][j] = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (!user) {\n\t\t\tif (!k) { \n\t\t\t\tbest_i = rand() % 3;\n\t\t\t\tbest_j = rand() % 3;\n\t\t\t} else\n\t\t\t\ttest_move(-1, 0);\n\n\t\t\tb[best_i][best_j] = -1;\n\t\t\tprintf(\"My move: %d\\n\", best_i * 3 + best_j + 1);\n\t\t}\n\n\t\tshowboard();\n\t\tif ((win = check_winner())) \n\t\t\treturn win == 1 ? \"You win.\\n\\n\": \"I win.\\n\\n\";\n\t}\n\treturn \"A draw.\\n\\n\";\n}\n\nint main()\n{\n\tint first = 0;\n\twhile (1) printf(\"%s\", game(first = !first));\n\treturn 0;\n}\n", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n"}
{"id": 39384, "name": "Integer sequence", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 39385, "name": "Integer sequence", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 39386, "name": "Integer sequence", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 39387, "name": "Entropy_Narcissist", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n"}
{"id": 39388, "name": "Entropy_Narcissist", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n"}
{"id": 39389, "name": "DNS query", "C": "#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\t\t\n#include <stdio.h>\t\t\n#include <stdlib.h>\t\t\n#include <string.h>\t\t\n\nint\nmain()\n{\n\tstruct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n\t\n\tmemset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;     \n\thints.ai_socktype = SOCK_DGRAM;  \n\n\t\n\terror = getaddrinfo(\"www.kame.net\", NULL, &hints, &res0);\n\tif (error) {\n\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\texit(1);\n\t}\n\n\t\n\tfor (res = res0; res; res = res->ai_next) {\n\t\t\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\n\t\tif (error) {\n\t\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\\n\", host);\n\t\t}\n\t}\n\n\t\n\tfreeaddrinfo(res0);\n\n\treturn 0;\n}\n", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n"}
{"id": 39390, "name": "Peano curve", "C": "\n\n#include <graphics.h>\n#include <math.h>\n\nvoid Peano(int x, int y, int lg, int i1, int i2) {\n\n\tif (lg == 1) {\n\t\tlineto(3*x,3*y);\n\t\treturn;\n\t}\n\t\n\tlg = lg/3;\n\tPeano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2);\n\tPeano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2);\n\tPeano(x+lg, y+lg, lg, i1, 1-i2);\n\tPeano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2);\n\tPeano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2);\n\tPeano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2);\n\tPeano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2);\n\tPeano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2);\n\tPeano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2);\n}\n\nint main(void) {\n\n\tinitwindow(1000,1000,\"Peano, Peano\");\n\n\tPeano(0, 0, 1000, 0, 0); \n\t\n\tgetch();\n\tcleardevice();\n\t\n\treturn 0;\n}\n", "Python": "import turtle as tt\nimport inspect\n\nstack = [] \ndef peano(iterations=1):\n    global stack\n\n    \n    ivan = tt.Turtle(shape = \"classic\", visible = True)\n\n\n    \n    screen = tt.Screen()\n    screen.title(\"Desenhin do Peano\")\n    screen.bgcolor(\"\n    screen.delay(0) \n    screen.setup(width=0.95, height=0.9)\n\n    \n    walk = 1\n\n    def screenlength(k):\n        \n        \n        if k != 0:\n            length = screenlength(k-1)\n            return 2*length + 1\n        else: return 0\n\n    kkkj = screenlength(iterations)\n    screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)\n    ivan.color(\"\n\n\n    \n    def step1(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n    def step2(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n\n    \n    ivan.left(90)\n    step2(iterations)\n\n    tt.done()\n\nif __name__ == \"__main__\":\n    peano(4)\n    import pylab as P \n    P.plot(stack)\n    P.show()\n"}
{"id": 39391, "name": "Seven-sided dice from five-sided dice", "C": "int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n \nint rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\nint main()\n{\n\tprintf(check(rand5, 5, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\tprintf(check(rand7, 7, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\treturn 0;\n}\n", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n"}
{"id": 39392, "name": "Solve the no connection puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <math.h>\n\nint connections[15][2] = {\n    {0, 2}, {0, 3}, {0, 4}, \n    {1, 3}, {1, 4}, {1, 5}, \n    {6, 2}, {6, 3}, {6, 4}, \n    {7, 3}, {7, 4}, {7, 5}, \n    {2, 3}, {3, 4}, {4, 5}, \n};\n\nint pegs[8];\nint num = 0;\n\nbool valid() {\n    int i;\n    for (i = 0; i < 15; i++) {\n        if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid swap(int *a, int *b) {\n    int t = *a;\n    *a = *b;\n    *b = t;\n}\n\nvoid printSolution() {\n    printf(\"----- %d -----\\n\", num++);\n    printf(\"  %d %d\\n\",  pegs[0], pegs[1]);\n    printf(\"%d %d %d %d\\n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n    printf(\"  %d %d\\n\",  pegs[6], pegs[7]);\n    printf(\"\\n\");\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        int i;\n        for (i = le; i <= ri; i++) {\n            swap(pegs + le, pegs + i);\n            solution(le + 1, ri);\n            swap(pegs + le, pegs + i);\n        }\n    }\n}\n\nint main() {\n    int i;\n    for (i = 0; i < 8; i++) {\n        pegs[i] = i + 1;\n    }\n\n    solution(0, 8 - 1);\n    return 0;\n}\n", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n"}
{"id": 39393, "name": "Extensible prime generator", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#define CHUNK_BYTES (32 << 8)\n#define CHUNK_SIZE (CHUNK_BYTES << 6)\n\nint field[CHUNK_BYTES];\n#define GET(x) (field[(x)>>6] &  1<<((x)>>1&31))\n#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))\n\ntypedef unsigned uint;\ntypedef struct {\n        uint *e;\n        uint cap, len;\n} uarray;\nuarray primes, offset;\n\nvoid push(uarray *a, uint n)\n{\n        if (a->len >= a->cap) {\n                if (!(a->cap *= 2)) a->cap = 16;\n                a->e = realloc(a->e, sizeof(uint) * a->cap);\n        }\n        a->e[a->len++] = n;\n}\n\nuint low;\nvoid init(void)\n{\n        uint p, q;\n\n        unsigned char f[1<<16];\n        memset(f, 0, sizeof(f));\n        push(&primes, 2);\n        push(&offset, 0);\n        for (p = 3; p < 1<<16; p += 2) {\n                if (f[p]) continue;\n                for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;\n                push(&primes, p);\n                push(&offset, q);\n        }\n        low = 1<<16;\n}\n\nvoid sieve(void)\n{\n        uint i, p, q, hi, ptop;\n        if (!low) init();\n\n        memset(field, 0, sizeof(field));\n\n        hi = low + CHUNK_SIZE;\n        ptop = sqrt(hi) * 2 + 1;\n\n        for (i = 1; (p = primes.e[i]*2) < ptop; i++) {\n                for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)\n                        SET(q);\n                offset.e[i] = q + low;\n        }\n\n        for (p = 1; p < CHUNK_SIZE; p += 2)\n                if (!GET(p)) push(&primes, low + p);\n\n        low = hi;\n}\n\nint main(void)\n{\n        uint i, p, c;\n\n        while (primes.len < 20) sieve();\n        printf(\"First 20:\");\n        for (i = 0; i < 20; i++)\n                printf(\" %u\", primes.e[i]);\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 150) sieve();\n        printf(\"Between 100 and 150:\");\n        for (i = 0; i < primes.len; i++) {\n                if ((p = primes.e[i]) >= 100 && p < 150)\n                        printf(\" %u\", primes.e[i]);\n        }\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 8000) sieve();\n        for (i = c = 0; i < primes.len; i++)\n                if ((p = primes.e[i]) >= 7700 && p < 8000) c++;\n        printf(\"%u primes between 7700 and 8000\\n\", c);\n\n        for (c = 10; c <= 100000000; c *= 10) {\n                while (primes.len < c) sieve();\n                printf(\"%uth prime: %u\\n\", c, primes.e[c-1]);\n        }\n\n        return 0;\n}\n", "Python": "islice(count(7), 0, None, 2)\n"}
{"id": 39394, "name": "Rock-paper-scissors", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define LEN 3 \n\n\nint rand_idx(double *p, int n)\n{\n\tdouble s = rand() / (RAND_MAX + 1.0);\n\tint i;\n\tfor (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);\n\treturn i;\n}\n\nint main()\n{\n\tint user_action, my_action;\n\tint user_rec[] = {0, 0, 0};\n\tconst char *names[] = { \"Rock\", \"Paper\", \"Scissors\" };\n\tchar str[2];\n\tconst char *winner[] = { \"We tied.\", \"Meself winned.\", \"You win.\" };\n\tdouble  p[LEN] = { 1./3, 1./3, 1./3 };\n \n\twhile (1) {\n\t\tmy_action = rand_idx(p,LEN);\n \n\t\tprintf(\"\\nYour choice [1-3]:\\n\"\n\t\t\t\"  1. Rock\\n  2. Paper\\n  3. Scissors\\n> \");\n \n\t\t\n\t\tif (!scanf(\"%d\", &user_action)) {\n\t\t\tscanf(\"%1s\", str);\n\t\t\tif (*str == 'q') {\n\t\t\t\tprintf(\"Your choices [rock : %d , paper :  %d , scissors %d] \",user_rec[0],user_rec[1], user_rec[2]); \n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tuser_action --;\n\t\tif (user_action > 2 || user_action < 0) {\n\t\t\tprintf(\"invalid choice; again\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tprintf(\"You chose %s; I chose %s. %s\\n\",\n\t\t\tnames[user_action], names[my_action],\n\t\t\twinner[(my_action - user_action + 3) % 3]);\n \n\t\tuser_rec[user_action]++;\n\t}\n}\n", "Python": "from random import choice\n\nrules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}\nprevious = ['rock', 'paper', 'scissors']\n\nwhile True:\n    human = input('\\nchoose your weapon: ')\n    computer = rules[choice(previous)]  \n\n    if human in ('quit', 'exit'): break\n\n    elif human in rules:\n        previous.append(human)\n        print('the computer played', computer, end='; ')\n\n        if rules[computer] == human:  \n            print('yay you win!')\n        elif rules[human] == computer:  \n            print('the computer beat you... :(')\n        else: print(\"it's a tie!\")\n\n    else: print(\"that's not a valid choice\")\n"}
{"id": 39395, "name": "Create a two-dimensional array at runtime", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n   int user1 = 0, user2 = 0;\n   printf(\"Enter two integers.  Space delimited, please:  \");\n   scanf(\"%d %d\",&user1, &user2);\n   int array[user1][user2];\n   array[user1/2][user2/2] = user1 + user2;\n   printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n\n   return 0;\n}\n", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n"}
{"id": 39396, "name": "Chinese remainder theorem", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n"}
{"id": 39397, "name": "Chinese remainder theorem", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n"}
{"id": 39398, "name": "Vigenère cipher_Cryptanalysis", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *encoded =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\"\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\"\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\"\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\"\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\"\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\"\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\"\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\"\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\"\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\"\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\"\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\"\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\"\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\"\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\"\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\"\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n\nint best_match(const double *a, const double *b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n\n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n\n    return best_rotate;\n}\n\ndouble freq_every_nth(const int *msg, int len, int interval, char *key) {\n    double sum, d, ret;\n    double out[26], accu[26] = {0};\n    int i, j, rot;\n\n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n        key[j] = rot = best_match(out, freq);\n        key[j] += 'A';\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n\n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n\n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n\n    key[interval] = '\\0';\n    return ret;\n}\n\nint main() {\n    int txt[strlen(encoded)];\n    int len = 0, j;\n    char key[100];\n    double fit, best_fit = 1e100;\n\n    for (j = 0; encoded[j] != '\\0'; j++)\n        if (isupper(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n\n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        printf(\"%f, key length: %2d, %s\", fit, j, key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            printf(\" <--- best so far\");\n        }\n        printf(\"\\n\");\n    }\n\n    return 0;\n}\n", "Python": "from string import uppercase\nfrom operator import itemgetter\n\ndef vigenere_decrypt(target_freqs, input):\n    nchars = len(uppercase)\n    ordA = ord('A')\n    sorted_targets = sorted(target_freqs)\n\n    def frequency(input):\n        result = [[c, 0.0] for c in uppercase]\n        for c in input:\n            result[c - ordA][1] += 1\n        return result\n\n    def correlation(input):\n        result = 0.0\n        freq = frequency(input)\n        freq.sort(key=itemgetter(1))\n\n        for i, f in enumerate(freq):\n            result += f[1] * sorted_targets[i]\n        return result\n\n    cleaned = [ord(c) for c in input.upper() if c.isupper()]\n    best_len = 0\n    best_corr = -100.0\n\n    \n    \n    for i in xrange(2, len(cleaned) // 20):\n        pieces = [[] for _ in xrange(i)]\n        for j, c in enumerate(cleaned):\n            pieces[j % i].append(c)\n\n        \n        \n        corr = -0.5 * i + sum(correlation(p) for p in pieces)\n\n        if corr > best_corr:\n            best_len = i\n            best_corr = corr\n\n    if best_len == 0:\n        return (\"Text is too short to analyze\", \"\")\n\n    pieces = [[] for _ in xrange(best_len)]\n    for i, c in enumerate(cleaned):\n        pieces[i % best_len].append(c)\n\n    freqs = [frequency(p) for p in pieces]\n\n    key = \"\"\n    for fr in freqs:\n        fr.sort(key=itemgetter(1), reverse=True)\n\n        m = 0\n        max_corr = 0.0\n        for j in xrange(nchars):\n            corr = 0.0\n            c = ordA + j\n            for frc in fr:\n                d = (ord(frc[0]) - c + nchars) % nchars\n                corr += frc[1] * target_freqs[d]\n\n            if corr > max_corr:\n                m = j\n                max_corr = corr\n\n        key += chr(m + ordA)\n\n    r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)\n         for i, c in enumerate(cleaned))\n    return (key, \"\".join(r))\n\n\ndef main():\n    encoded = \n\n    english_frequences = [\n        0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n        0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n        0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n        0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\n    (key, decoded) = vigenere_decrypt(english_frequences, encoded)\n    print \"Key:\", key\n    print \"\\nText:\", decoded\n\nmain()\n"}
{"id": 39399, "name": "Pi", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\nmpz_t tmp1, tmp2, t5, t239, pows;\nvoid actan(mpz_t res, unsigned long base, mpz_t pows)\n{\n\tint i, neg = 1;\n\tmpz_tdiv_q_ui(res, pows, base);\n\tmpz_set(tmp1, res);\n\tfor (i = 3; ; i += 2) {\n\t\tmpz_tdiv_q_ui(tmp1, tmp1, base * base);\n\t\tmpz_tdiv_q_ui(tmp2, tmp1, i);\n\t\tif (mpz_cmp_ui(tmp2, 0) == 0) break;\n\t\tif (neg) mpz_sub(res, res, tmp2);\n\t\telse\t  mpz_add(res, res, tmp2);\n\t\tneg = !neg;\n\t}\n}\n\nchar * get_digits(int n, size_t* len)\n{\n\tmpz_ui_pow_ui(pows, 10, n + 20);\n\n\tactan(t5, 5, pows);\n\tmpz_mul_ui(t5, t5, 16);\n\n\tactan(t239, 239, pows);\n\tmpz_mul_ui(t239, t239, 4);\n\n\tmpz_sub(t5, t5, t239);\n\tmpz_ui_pow_ui(pows, 10, 20);\n\tmpz_tdiv_q(t5, t5, pows);\n\n\t*len = mpz_sizeinbase(t5, 10);\n\treturn mpz_get_str(0, 0, t5);\n}\n\nint main(int c, char **v)\n{\n\tunsigned long accu = 16384, done = 0;\n\tsize_t got;\n\tchar *s;\n\n\tmpz_init(tmp1);\n\tmpz_init(tmp2);\n\tmpz_init(t5);\n\tmpz_init(t239);\n\tmpz_init(pows);\n\n\twhile (1) {\n\t\ts = get_digits(accu, &got);\n\n\t\t\n\t\tgot -= 2; \n\t\twhile (s[got] == '0' || s[got] == '9') got--;\n\n\t\tprintf(\"%.*s\", (int)(got - done), s + done);\n\t\tfree(s);\n\n\t\tdone = got;\n\n\t\t\n\t\taccu *= 2;\n\t}\n\n\treturn 0;\n}\n", "Python": "def calcPi():\n    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n    while True:\n        if 4*q+r-t < n*t:\n            yield n\n            nr = 10*(r-n*t)\n            n  = ((10*(3*q+r))//t)-10*n\n            q  *= 10\n            r  = nr\n        else:\n            nr = (2*q+r)*l\n            nn = (q*(7*k)+2+(r*l))//(t*l)\n            q  *= k\n            t  *= l\n            l  += 2\n            k += 1\n            n  = nn\n            r  = nr\n\nimport sys\npi_digits = calcPi()\ni = 0\nfor d in pi_digits:\n    sys.stdout.write(str(d))\n    i += 1\n    if i == 40: print(\"\"); i = 0\n"}
{"id": 39400, "name": "Hofstadter Q sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n"}
{"id": 39401, "name": "Hofstadter Q sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n"}
{"id": 39402, "name": "Bitwise operations", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 39403, "name": "Dragon curve", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n"}
{"id": 39404, "name": "Read a file line by line", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 39405, "name": "Doubly-linked list_Element insertion", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 39406, "name": "Smarandache prime-digital sequence", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n"}
{"id": 39407, "name": "Smarandache prime-digital sequence", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n"}
{"id": 39408, "name": "Quickselect algorithm", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 39409, "name": "Non-decimal radices_Convert", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 39410, "name": "Walk a directory_Recursively", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 39411, "name": "State name puzzle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n"}
{"id": 39412, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 39413, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 39414, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 39415, "name": "Classes", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 39416, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 39417, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 39418, "name": "LZW compression", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n"}
{"id": 39419, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 39420, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 39421, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 39422, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 39423, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 39424, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 39425, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 39426, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 39427, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 39428, "name": "Mertens function", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n"}
{"id": 39429, "name": "Order by pair comparisons", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n"}
{"id": 39430, "name": "Order by pair comparisons", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n"}
{"id": 39431, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 39432, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 39433, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 39434, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 39435, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 39436, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 39437, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 39438, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 39439, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 39440, "name": "Legendre prime counting function", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n"}
{"id": 39441, "name": "Use another language to call a function", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n"}
{"id": 39442, "name": "Longest string challenge", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 39443, "name": "Create a file", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 39444, "name": "Unprimeable numbers", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 39445, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 39446, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 39447, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 39448, "name": "Chernick's Carmichael numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n"}
{"id": 39449, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 39450, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 39451, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 39452, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 39453, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 39454, "name": "Sequence of primorial primes", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n"}
{"id": 39455, "name": "Sequence of primorial primes", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n"}
{"id": 39456, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 39457, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 39458, "name": "Dining philosophers", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n"}
{"id": 39459, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 39460, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 39461, "name": "Logistic curve fitting in epidemiology", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n"}
{"id": 39462, "name": "Sorting algorithms_Strand sort", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n"}
{"id": 39463, "name": "Additive primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n"}
{"id": 39464, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 39465, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 39466, "name": "Delegates", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n"}
{"id": 39467, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 39468, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 39469, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 39470, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 39471, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 39472, "name": "Enforced immutability", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n"}
{"id": 39473, "name": "Sutherland-Hodgman polygon clipping", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n"}
{"id": 39474, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 39475, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 39476, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n"}
{"id": 39477, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n"}
{"id": 39478, "name": "Optional parameters", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n"}
{"id": 39479, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 39480, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 39481, "name": "Call a foreign-language function", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 39482, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 39483, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 39484, "name": "Faulhaber's triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n"}
{"id": 39485, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 39486, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 39487, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 39488, "name": "Array concatenation", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 39489, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 39490, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 39491, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 39492, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 39493, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 39494, "name": "Primes - allocate descendants to their ancestors", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n"}
{"id": 39495, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 39496, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 39497, "name": "First-class functions", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n"}
{"id": 39498, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 39499, "name": "XML_Output", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n"}
{"id": 39500, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 39501, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 39502, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 39503, "name": "Regular expressions", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 39504, "name": "Guess the number_With feedback (player)", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n"}
{"id": 39505, "name": "Hash from two arrays", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 39506, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 39507, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 39508, "name": "Fractal tree", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n"}
{"id": 39509, "name": "Colour pinstripe_Display", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 39510, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 39511, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 39512, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 39513, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n"}
{"id": 39514, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n"}
{"id": 39515, "name": "Animate a pendulum", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n"}
{"id": 39516, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 39517, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 39518, "name": "Create a file on magnetic tape", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n"}
{"id": 39519, "name": "Sorting algorithms_Heapsort", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n"}
{"id": 39520, "name": "Playing cards", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 39521, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 39522, "name": "Sierpinski carpet", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 39523, "name": "Sorting algorithms_Bogosort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 39524, "name": "Euler method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n"}
{"id": 39525, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 39526, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 39527, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 39528, "name": "JortSort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n"}
{"id": 39529, "name": "Leap year", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 39530, "name": "Combinations and permutations", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n"}
{"id": 39531, "name": "Sort numbers lexicographically", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n"}
{"id": 39532, "name": "Number names", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 39533, "name": "Compare length of two strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 39534, "name": "Sorting algorithms_Shell sort", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n"}
{"id": 39535, "name": "Doubly-linked list_Definition", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 39536, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 39537, "name": "Permutation test", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n"}
{"id": 39538, "name": "Möbius function", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n"}
{"id": 39539, "name": "Increment a numerical string", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 39540, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 39541, "name": "Sorting algorithms_Permutation sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n"}
{"id": 39542, "name": "Averages_Arithmetic mean", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 39543, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 39544, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 39545, "name": "Entropy", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n"}
{"id": 39546, "name": "Tokenize a string with escaping", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n"}
{"id": 39547, "name": "Hello world_Text", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 39548, "name": "Sexy primes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef unsigned char bool;\n\nvoid sieve(bool *c, int limit) {\n    int i, p = 3, p2;\n    \n    c[0] = TRUE;\n    c[1] = TRUE;\n    \n    for (;;) {\n        p2 = p * p;\n        if (p2 >= limit) {\n            break;\n        }\n        for (i = p2; i < limit; i += 2*p) {\n            c[i] = TRUE;\n        }\n        for (;;) {\n            p += 2;\n            if (!c[p]) {\n                break;\n            }\n        }\n    }\n}\n\nvoid printHelper(const char *cat, int len, int lim, int n) {\n    const char *sp = strcmp(cat, \"unsexy primes\") ? \"sexy prime \" : \"\";\n    const char *verb = (len == 1) ? \"is\" : \"are\";\n    printf(\"Number of %s%s less than %'d = %'d\\n\", sp, cat, lim, len);\n    printf(\"The last %d %s:\\n\", n, verb);\n}\n\nvoid printArray(int *a, int len) {\n    int i;\n    printf(\"[\");\n    for (i = 0; i < len; ++i) printf(\"%d \", a[i]);\n    printf(\"\\b]\");\n}\n\nint main() {\n    int i, ix, n, lim = 1000035;\n    int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;\n    int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;\n    int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;\n    int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];\n    int last_un[10];\n    bool *sv = calloc(lim - 1, sizeof(bool)); \n    setlocale(LC_NUMERIC, \"\");\n    sieve(sv, lim);\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            unsexy++;\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pairs++;\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            trips++;\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            quads++;\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            quins++;\n        }\n    }\n    if (pairs < lpr) lpr = pairs;\n    if (trips < ltr) ltr = trips;\n    if (quads < lqd) lqd = quads;\n    if (quins < lqn) lqn = quins;\n    if (unsexy < lun) lun = unsexy;\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            un++;\n            if (un > unsexy - lun) {\n                last_un[un + lun - 1 - unsexy] = i;\n            }\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pr++;\n            if (pr > pairs - lpr) {\n                ix = pr + lpr - 1 - pairs;\n                last_pr[ix][0] = i; last_pr[ix][1] = i + 6;\n            }\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            tr++;\n            if (tr > trips - ltr) {\n                ix = tr + ltr - 1 - trips;\n                last_tr[ix][0] = i; last_tr[ix][1] = i + 6;\n                last_tr[ix][2] = i + 12;\n            }\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            qd++;\n            if (qd > quads - lqd) {\n                ix = qd + lqd - 1 - quads;\n                last_qd[ix][0] = i; last_qd[ix][1] = i + 6;\n                last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;\n            }\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            qn++;\n            if (qn > quins - lqn) {\n                ix = qn + lqn - 1 - quins;\n                last_qn[ix][0] = i; last_qn[ix][1] = i + 6;\n                last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;\n                last_qn[ix][4] = i + 24;\n            }\n        }\n    }\n\n    printHelper(\"pairs\", pairs, lim, lpr);\n    printf(\"  [\");\n    for (i = 0; i < lpr; ++i) {\n        printArray(last_pr[i], 2);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"triplets\", trips, lim, ltr);\n    printf(\"  [\");\n    for (i = 0; i < ltr; ++i) {\n        printArray(last_tr[i], 3);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quadruplets\", quads, lim, lqd);\n    printf(\"  [\");\n    for (i = 0; i < lqd; ++i) {\n        printArray(last_qd[i], 4);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quintuplets\", quins, lim, lqn);\n    printf(\"  [\");\n    for (i = 0; i < lqn; ++i) {\n        printArray(last_qn[i], 5);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"unsexy primes\", unsexy, lim, lun);\n    printf(\"  [\");\n    printArray(last_un, lun);\n    printf(\"\\b]\\n\");\n    free(sv);\n    return 0;\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 39549, "name": "Forward difference", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 39550, "name": "Primality by trial division", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 39551, "name": "Evaluate binomial coefficients", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 39552, "name": "Collections", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 39553, "name": "Singly-linked list_Traversal", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n"}
{"id": 39554, "name": "Bitmap_Write a PPM file", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 39555, "name": "Delete a file", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 39556, "name": "Discordian date", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 39557, "name": "Flipping bits game", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 39558, "name": "Flipping bits game", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 39559, "name": "Flipping bits game", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 39560, "name": "Hickerson series of almost integers", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 39561, "name": "Hickerson series of almost integers", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 39562, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 39563, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 39564, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 39565, "name": "String interpolation (included)", "C": "#include <stdio.h>\n\nint main() {\n  const char *extra = \"little\";\n  printf(\"Mary had a %s lamb.\\n\", extra);\n  return 0;\n}\n", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n"}
{"id": 39566, "name": "Sorting algorithms_Patience sort", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint* patienceSort(int* arr,int size){\n\tint decks[size][size],i,j,min,pickedRow;\n\t\n\tint *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){\n\t\t\t\tdecks[j][count[j]] = arr[i];\n\t\t\t\tcount[j]++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmin = decks[0][count[0]-1];\n\tpickedRow = 0;\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]>0 && decks[j][count[j]-1]<min){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t}\n\t\t}\n\t\tsortedArr[i] = min;\n\t\tcount[pickedRow]--;\n\t\t\n\t\tfor(j=0;j<size;j++)\n\t\t\tif(count[j]>0){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\t\n\tfree(count);\n\tfree(decks);\n\t\n\treturn sortedArr;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr, *sortedArr, i;\n\t\n\tif(argC==0)\n\t\tprintf(\"Usage : %s <integers to be sorted separated by space>\");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i<=argC;i++)\n\t\t\tarr[i-1] = atoi(argV[i]);\n\t\t\n\t\tsortedArr = patienceSort(arr,argC-1);\n\t\t\n\t\tfor(i=0;i<argC-1;i++)\n\t\t\tprintf(\"%d \",sortedArr[i]);\n\t}\n\t\n\treturn 0;\n}\n", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n"}
{"id": 39567, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 39568, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 39569, "name": "Tau number", "C": "#include <stdio.h>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    unsigned int p;\n\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int count = 0;\n    unsigned int n;\n\n    printf(\"The first %d tau numbers are:\\n\", limit);\n    for (n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            printf(\"%6d\", n);\n            ++count;\n            if (count % 10 == 0) {\n                printf(\"\\n\");\n            }\n        }\n    }\n\n    return 0;\n}\n", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n"}
{"id": 39570, "name": "Determinant and permanent", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 39571, "name": "Determinant and permanent", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 39572, "name": "Partition function P", "C": "#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <gmp.h>\n\nmpz_t* partition(uint64_t n) {\n\tmpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));\n\tmpz_init_set_ui(pn[0], 1);\n\tmpz_init_set_ui(pn[1], 1);\n\tfor (uint64_t i = 2; i < n + 2; i ++) {\n\t\tmpz_init(pn[i]);\n\t\tfor (uint64_t k = 1, penta; ; k++) {\n\t\t\tpenta = k * (3 * k - 1) >> 1;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t\tpenta += k;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t}\n\t}\n\tmpz_t *tmp = &pn[n + 1];\n\tfor (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);\n\tfree(pn);\n\treturn tmp;\n}\n\nint main(int argc, char const *argv[]) {\n\tclock_t start = clock();\n\tmpz_t *p = partition(6666);\n\tgmp_printf(\"%Zd\\n\", p);\n\tprintf(\"Elapsed time: %.04f seconds\\n\",\n\t\t(double)(clock() - start) / (double)CLOCKS_PER_SEC);\n\treturn 0;\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n"}
{"id": 39573, "name": "Bitwise operations", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n"}
{"id": 39574, "name": "Dragon curve", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n"}
{"id": 39575, "name": "Read a file line by line", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n"}
{"id": 39576, "name": "Doubly-linked list_Element insertion", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n"}
{"id": 39577, "name": "Quickselect algorithm", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 39578, "name": "Non-decimal radices_Convert", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 39579, "name": "Walk a directory_Recursively", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 39580, "name": "CRC-32", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 39581, "name": "Classes", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n"}
{"id": 39582, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 39583, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 39584, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 39585, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 39586, "name": "Anonymous recursion", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n"}
{"id": 39587, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 39588, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 39589, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 39590, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n"}
{"id": 39591, "name": "Delegates", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 39592, "name": "Delegates", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 39593, "name": "Enforced immutability", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n", "C#": "readonly DateTime now = DateTime.Now;\n"}
{"id": 39594, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 39595, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 39596, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 39597, "name": "Spiral matrix", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n"}
{"id": 39598, "name": "Faulhaber's triangle", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 39599, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 39600, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 39601, "name": "Array concatenation", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 39602, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n"}
{"id": 39603, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 39604, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 39605, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 39606, "name": "First-class functions", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n"}
{"id": 39607, "name": "Proper divisors", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 39608, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n"}
{"id": 39609, "name": "Regular expressions", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n"}
{"id": 39610, "name": "Guess the number_With feedback (player)", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n"}
{"id": 39611, "name": "Hash from two arrays", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n"}
{"id": 39612, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 39613, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 39614, "name": "Animate a pendulum", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n"}
{"id": 39615, "name": "Sorting algorithms_Heapsort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n"}
{"id": 39616, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 39617, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 39618, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 39619, "name": "Sierpinski carpet", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n"}
{"id": 39620, "name": "Sorting algorithms_Bogosort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 39621, "name": "Merge and aggregate datasets", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n"}
{"id": 39622, "name": "Euler method", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 39623, "name": "Sequence of non-squares", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 39624, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 39625, "name": "JortSort", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n"}
{"id": 39626, "name": "Leap year", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n"}
{"id": 39627, "name": "Sort numbers lexicographically", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n"}
{"id": 39628, "name": "Number names", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n"}
{"id": 39629, "name": "Compare length of two strings", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n"}
{"id": 39630, "name": "Letter frequency", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 39631, "name": "Increment a numerical string", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 39632, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 39633, "name": "Averages_Arithmetic mean", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n"}
{"id": 39634, "name": "Entropy", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n"}
{"id": 39635, "name": "Tokenize a string with escaping", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n"}
{"id": 39636, "name": "Hello world_Text", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 39637, "name": "Forward difference", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 39638, "name": "Primality by trial division", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 39639, "name": "Evaluate binomial coefficients", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 39640, "name": "Collections", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 39641, "name": "Singly-linked list_Traversal", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n"}
{"id": 39642, "name": "Bitmap_Write a PPM file", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 39643, "name": "Delete a file", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n"}
{"id": 39644, "name": "Discordian date", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n"}
{"id": 39645, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 39646, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 39647, "name": "String interpolation (included)", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n"}
{"id": 39648, "name": "String interpolation (included)", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n"}
{"id": 39649, "name": "Partition function P", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 39650, "name": "Partition function P", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 39651, "name": "Numbers with prime digits whose sum is 13", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 39652, "name": "Bitwise operations", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 39653, "name": "Dragon curve", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n"}
{"id": 39654, "name": "Read a file line by line", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 39655, "name": "Doubly-linked list_Element insertion", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n"}
{"id": 39656, "name": "Doubly-linked list_Element insertion", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n"}
{"id": 39657, "name": "Smarandache prime-digital sequence", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n"}
{"id": 39658, "name": "Quickselect algorithm", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n"}
{"id": 39659, "name": "Non-decimal radices_Convert", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n", "Python": "i = int('1a',16)  \n"}
{"id": 39660, "name": "Walk a directory_Recursively", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 39661, "name": "Main step of GOST 28147-89", "C++": "UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)\n{\n    UINT_64 N;\n\tN = N1;\n\tN = (N<<32)|N2;\n\treturn UINT_64(N);\n}\n\nUINT_32 TGost::ReplaceBlock(UINT_32 x)\n{   \n    register i;\n    UINT_32 res = 0UL;\n    for(i=7;i>=0;i--)\n    {\n       ui4_0 = x>>(i*4);\n       ui4_0 = BS[ui4_0][i];\n       res = (res<<4)|ui4_0;\n    }\n    return res;\n}\n\nUINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)\n{\n   UINT_32 N1,N2,S=0UL;\n   N1=UINT_32(N);\n   N2=N>>32;\n   S = N1 + X % 0x4000000000000;\n   S = ReplaceBlock(S);\n   S = (S<<11)|(S>>21);\n   S ^= N2;\n   N2 = N1;\n   N1 = S;\n   return SWAP32(N2,N1);\n}\n", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n"}
{"id": 39662, "name": "State name puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n"}
{"id": 39663, "name": "CRC-32", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 39664, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 39665, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 39666, "name": "Classes", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 39667, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 39668, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 39669, "name": "LZW compression", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 39670, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 39671, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 39672, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 39673, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 39674, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 39675, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 39676, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 39677, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 39678, "name": "Mertens function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n"}
{"id": 39679, "name": "Mertens function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n"}
{"id": 39680, "name": "Order by pair comparisons", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n"}
{"id": 39681, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 39682, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 39683, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 39684, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 39685, "name": "Anonymous recursion", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 39686, "name": "Snake", "C++": "#include <windows.h>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nconst int WID = 60, HEI = 30, MAX_LEN = 600;\nenum DIR { NORTH, EAST, SOUTH, WEST };\n\nclass snake {\npublic:\n    snake() {\n        console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( \"Snake\" ); \n        COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );\n        SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );\n        CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );\n    }\n    void play() {\n        std::string a;\n        while( 1 ) {\n            createField(); alive = true;\n            while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }\n            COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );\n            SetConsoleTextAttribute( console, 0x000b );\n            std::cout << \"Play again [Y/N]? \"; std::cin >> a;\n            if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;\n        }\n    }\nprivate:\n    void createField() {\n        COORD coord = { 0, 0 }; DWORD c;\n        FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );\n        FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );\n        SetConsoleCursorPosition( console, coord );\n        int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;\n        for( x = 0; x < WID; x++ ) {\n            brd[x] = brd[x + WID * ( HEI - 1 )] = '+';\n        }\n        for( ; y < HEI; y++ ) {\n            brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';\n        }\n        do {\n            x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n        } while( brd[x + WID * y] );\n        brd[x + WID * y] = '@';\n        tailIdx = 0; headIdx = 4; x = 3; y = 2;\n        for( int c = tailIdx; c < headIdx; c++ ) {\n            brd[x + WID * y] = '#';\n            snk[c].X = 3 + c; snk[c].Y = 2;\n        }\n        head = snk[3]; dir = EAST; points = 0;\n    }\n    void readKey() {\n        if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;\n        if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;\n        if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;\n        if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;\n    }\n    void drawField() {\n        COORD coord; char t;\n        for( int y = 0; y < HEI; y++ ) {\n            coord.Y = y;\n            for( int x = 0; x < WID; x++ ) {\n                t = brd[x + WID * y]; if( !t ) continue;\n                coord.X = x; SetConsoleCursorPosition( console, coord );\n                if( coord.X == head.X && coord.Y == head.Y ) {\n                    SetConsoleTextAttribute( console, 0x002e );\n                    std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );\n                    continue;\n                }\n                switch( t ) {\n                    case '#': SetConsoleTextAttribute( console, 0x002a ); break;\n                    case '+': SetConsoleTextAttribute( console, 0x0019 ); break;\n                    case '@': SetConsoleTextAttribute( console, 0x004c ); break;\n                }\n                std::cout << t; SetConsoleTextAttribute( console, 0x0000 );\n            }\n        }\n        std::cout << t; SetConsoleTextAttribute( console, 0x0007 );\n        COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );\n        std::cout << \"Points: \" << points;\n    }\n    void moveSnake() {\n        switch( dir ) {\n            case NORTH: head.Y--; break;\n            case EAST: head.X++; break;\n            case SOUTH: head.Y++; break;\n            case WEST: head.X--; break;\n        }\n        char t = brd[head.X + WID * head.Y];\n        if( t && t != '@' ) { alive = false; return; }\n        brd[head.X + WID * head.Y] = '#';\n        snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;\n        if( ++headIdx >= MAX_LEN ) headIdx = 0;\n        if( t == '@' ) {\n            points++; int x, y;\n            do {\n                x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n            } while( brd[x + WID * y] );\n            brd[x + WID * y] = '@'; return;\n        }\n        SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';\n        brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;\n        if( ++tailIdx >= MAX_LEN ) tailIdx = 0;\n    }\n    bool alive; char brd[WID * HEI]; \n    HANDLE console; DIR dir; COORD snk[MAX_LEN];\n    COORD head; int tailIdx, headIdx, points;\n};\nint main( int argc, char* argv[] ) {\n    srand( static_cast<unsigned>( time( NULL ) ) );\n    snake s; s.play(); return 0;\n}\n", "Python": "from __future__ import annotations\n\nimport itertools\nimport random\n\nfrom enum import Enum\n\nfrom typing import Any\nfrom typing import Tuple\n\nimport pygame as pg\n\nfrom pygame import Color\nfrom pygame import Rect\n\nfrom pygame.surface import Surface\n\nfrom pygame.sprite import AbstractGroup\nfrom pygame.sprite import Group\nfrom pygame.sprite import RenderUpdates\nfrom pygame.sprite import Sprite\n\n\nclass Direction(Enum):\n    UP = (0, -1)\n    DOWN = (0, 1)\n    LEFT = (-1, 0)\n    RIGHT = (1, 0)\n\n    def opposite(self, other: Direction):\n        return (self[0] + other[0], self[1] + other[1]) == (0, 0)\n\n    def __getitem__(self, i: int):\n        return self.value[i]\n\n\nclass SnakeHead(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        facing: Direction,\n        bounds: Rect,\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"aquamarine4\"))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n        self.facing = facing\n        self.size = size\n        self.speed = size\n        self.bounds = bounds\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        \n        self.rect.move_ip(\n            (\n                self.facing[0] * self.speed,\n                self.facing[1] * self.speed,\n            )\n        )\n\n        \n        if self.rect.right > self.bounds.right:\n            self.rect.left = 0\n        elif self.rect.left < 0:\n            self.rect.right = self.bounds.right\n\n        if self.rect.bottom > self.bounds.bottom:\n            self.rect.top = 0\n        elif self.rect.top < 0:\n            self.rect.bottom = self.bounds.bottom\n\n    def change_direction(self, direction: Direction):\n        if not self.facing == direction and not direction.opposite(self.facing):\n            self.facing = direction\n\n\nclass SnakeBody(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        colour: str = \"white\",\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(colour))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n\n\nclass Snake(RenderUpdates):\n    def __init__(self, game: Game) -> None:\n        self.segment_size = game.segment_size\n        self.colours = itertools.cycle([\"aquamarine1\", \"aquamarine3\"])\n\n        self.head = SnakeHead(\n            size=self.segment_size,\n            position=game.rect.center,\n            facing=Direction.RIGHT,\n            bounds=game.rect,\n        )\n\n        neck = [\n            SnakeBody(\n                size=self.segment_size,\n                position=game.rect.center,\n                colour=next(self.colours),\n            )\n            for _ in range(2)\n        ]\n\n        super().__init__(*[self.head, *neck])\n\n        self.body = Group()\n        self.tail = neck[-1]\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        self.head.update()\n\n        \n        segments = self.sprites()\n        for i in range(len(segments) - 1, 0, -1):\n            \n            segments[i].rect.center = segments[i - 1].rect.center\n\n    def change_direction(self, direction: Direction):\n        self.head.change_direction(direction)\n\n    def grow(self):\n        tail = SnakeBody(\n            size=self.segment_size,\n            position=self.tail.rect.center,\n            colour=next(self.colours),\n        )\n        self.tail = tail\n        self.add(self.tail)\n        self.body.add(self.tail)\n\n\nclass SnakeFood(Sprite):\n    def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None:\n        super().__init__(*groups)\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"red\"))\n        self.rect = self.image.get_rect()\n\n        self.rect.topleft = (\n            random.randint(0, game.rect.width),\n            random.randint(0, game.rect.height),\n        )\n\n        self.rect.clamp_ip(game.rect)\n\n        \n        \n        while pg.sprite.spritecollideany(self, game.snake):\n            self.rect.topleft = (\n                random.randint(0, game.rect.width),\n                random.randint(0, game.rect.height),\n            )\n\n            self.rect.clamp_ip(game.rect)\n\n\nclass Game:\n    def __init__(self) -> None:\n        self.rect = Rect(0, 0, 640, 480)\n        self.background = Surface(self.rect.size)\n        self.background.fill(Color(\"black\"))\n\n        self.score = 0\n        self.framerate = 16\n\n        self.segment_size = 10\n        self.snake = Snake(self)\n        self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size))\n\n        pg.init()\n\n    def _init_display(self) -> Surface:\n        bestdepth = pg.display.mode_ok(self.rect.size, 0, 32)\n        screen = pg.display.set_mode(self.rect.size, 0, bestdepth)\n\n        pg.display.set_caption(\"Snake\")\n        pg.mouse.set_visible(False)\n\n        screen.blit(self.background, (0, 0))\n        pg.display.flip()\n\n        return screen\n\n    def draw(self, screen: Surface):\n        dirty = self.snake.draw(screen)\n        pg.display.update(dirty)\n\n        dirty = self.food_group.draw(screen)\n        pg.display.update(dirty)\n\n    def update(self, screen):\n        self.food_group.clear(screen, self.background)\n        self.food_group.update()\n        self.snake.clear(screen, self.background)\n        self.snake.update()\n\n    def main(self) -> int:\n        screen = self._init_display()\n        clock = pg.time.Clock()\n\n        while self.snake.head.alive():\n            for event in pg.event.get():\n                if event.type == pg.QUIT or (\n                    event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q)\n                ):\n                    return self.score\n\n            \n            keystate = pg.key.get_pressed()\n\n            if keystate[pg.K_RIGHT]:\n                self.snake.change_direction(Direction.RIGHT)\n            elif keystate[pg.K_LEFT]:\n                self.snake.change_direction(Direction.LEFT)\n            elif keystate[pg.K_UP]:\n                self.snake.change_direction(Direction.UP)\n            elif keystate[pg.K_DOWN]:\n                self.snake.change_direction(Direction.DOWN)\n\n            \n            self.update(screen)\n\n            \n            for food in pg.sprite.spritecollide(\n                self.snake.head, self.food_group, dokill=False\n            ):\n                food.kill()\n                self.snake.grow()\n                self.score += 1\n\n                \n                if self.score % 5 == 0:\n                    self.framerate += 1\n\n                self.food_group.add(SnakeFood(self, self.segment_size))\n\n            \n            if pg.sprite.spritecollideany(self.snake.head, self.snake.body):\n                self.snake.head.kill()\n\n            self.draw(screen)\n            clock.tick(self.framerate)\n\n        return self.score\n\n\nif __name__ == \"__main__\":\n    game = Game()\n    score = game.main()\n    print(score)\n"}
{"id": 39687, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 39688, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 39689, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 39690, "name": "Legendre prime counting function", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n"}
{"id": 39691, "name": "Legendre prime counting function", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n"}
{"id": 39692, "name": "Use another language to call a function", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n"}
{"id": 39693, "name": "Longest string challenge", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 39694, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 39695, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 39696, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 39697, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 39698, "name": "Unprimeable numbers", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n"}
{"id": 39699, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 39700, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 39701, "name": "Chernick's Carmichael numbers", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n"}
{"id": 39702, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 39703, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 39704, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 39705, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 39706, "name": "Sequence of primorial primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n"}
{"id": 39707, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 39708, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 39709, "name": "Dining philosophers", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n"}
{"id": 39710, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 39711, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 39712, "name": "Logistic curve fitting in epidemiology", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n"}
{"id": 39713, "name": "Sorting algorithms_Strand sort", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n"}
{"id": 39714, "name": "Additive primes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 39715, "name": "Inverted syntax", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n", "Python": "x = truevalue if condition else falsevalue\n"}
{"id": 39716, "name": "Inverted syntax", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n", "Python": "x = truevalue if condition else falsevalue\n"}
{"id": 39717, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 39718, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 39719, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 39720, "name": "Delegates", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 39721, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 39722, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 39723, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39724, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39725, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39726, "name": "Enforced immutability", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 39727, "name": "Sutherland-Hodgman polygon clipping", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n"}
{"id": 39728, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 39729, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 39730, "name": "Spiral matrix", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n"}
{"id": 39731, "name": "Optional parameters", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n"}
{"id": 39732, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 39733, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 39734, "name": "Call a foreign-language function", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 39735, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 39736, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 39737, "name": "Faulhaber's triangle", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 39738, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 39739, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 39740, "name": "Word wheel", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n"}
{"id": 39741, "name": "Array concatenation", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 39742, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 39743, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 39744, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 39745, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 39746, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 39747, "name": "Primes - allocate descendants to their ancestors", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n"}
{"id": 39748, "name": "Primes - allocate descendants to their ancestors", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n"}
{"id": 39749, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 39750, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 39751, "name": "First-class functions", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 39752, "name": "Proper divisors", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 39753, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n"}
{"id": 39754, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 39755, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 39756, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 39757, "name": "Regular expressions", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 39758, "name": "Guess the number_With feedback (player)", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n"}
{"id": 39759, "name": "Hash from two arrays", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 39760, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 39761, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 39762, "name": "Fractal tree", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n"}
{"id": 39763, "name": "Colour pinstripe_Display", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n"}
{"id": 39764, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 39765, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 39766, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n"}
{"id": 39767, "name": "Animate a pendulum", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n"}
{"id": 39768, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 39769, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 39770, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 39771, "name": "Create a file on magnetic tape", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n"}
{"id": 39772, "name": "Sorting algorithms_Heapsort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n"}
{"id": 39773, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 39774, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 39775, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 39776, "name": "Sierpinski carpet", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 39777, "name": "Sorting algorithms_Bogosort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 39778, "name": "Merge and aggregate datasets", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n"}
{"id": 39779, "name": "Euler method", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n"}
{"id": 39780, "name": "Sequence of non-squares", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 39781, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 39782, "name": "JortSort", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n"}
{"id": 39783, "name": "Leap year", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 39784, "name": "Combinations and permutations", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n"}
{"id": 39785, "name": "Sort numbers lexicographically", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n"}
{"id": 39786, "name": "Number names", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 39787, "name": "Compare length of two strings", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 39788, "name": "Sorting algorithms_Shell sort", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 39789, "name": "Doubly-linked list_Definition", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n"}
{"id": 39790, "name": "Letter frequency", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 39791, "name": "Permutation test", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n"}
{"id": 39792, "name": "Möbius function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n"}
{"id": 39793, "name": "Increment a numerical string", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n", "Python": "next = str(int('123') + 1)\n"}
{"id": 39794, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 39795, "name": "Sorting algorithms_Permutation sort", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n"}
{"id": 39796, "name": "Averages_Arithmetic mean", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 39797, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39798, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 39799, "name": "Entropy", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 39800, "name": "Tokenize a string with escaping", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n"}
{"id": 39801, "name": "Hello world_Text", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n", "Python": "print \"Hello world!\"\n"}
{"id": 39802, "name": "Sexy primes", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n"}
{"id": 39803, "name": "Forward difference", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 39804, "name": "Primality by trial division", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 39805, "name": "Evaluate binomial coefficients", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 39806, "name": "Collections", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 39807, "name": "Singly-linked list_Traversal", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n", "Python": "for node in lst:\n    print node.value\n"}
{"id": 39808, "name": "Bitmap_Write a PPM file", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 39809, "name": "Delete a file", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 39810, "name": "Discordian date", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 39811, "name": "Flipping bits game", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 39812, "name": "Flipping bits game", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 39813, "name": "Flipping bits game", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 39814, "name": "Hickerson series of almost integers", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 39815, "name": "Hickerson series of almost integers", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 39816, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 39817, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 39818, "name": "String interpolation (included)", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 39819, "name": "String interpolation (included)", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 39820, "name": "Sorting algorithms_Patience sort", "C++": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <iterator>\n#include <algorithm>\n#include <cassert>\n\ntemplate <class E>\nstruct pile_less {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() < pile2.top();\n  }\n};\n\ntemplate <class E>\nstruct pile_greater {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() > pile2.top();\n  }\n};\n\n\ntemplate <class Iterator>\nvoid patience_sort(Iterator first, Iterator last) {\n  typedef typename std::iterator_traits<Iterator>::value_type E;\n  typedef std::stack<E> Pile;\n\n  std::vector<Pile> piles;\n  \n  for (Iterator it = first; it != last; it++) {\n    E& x = *it;\n    Pile newPile;\n    newPile.push(x);\n    typename std::vector<Pile>::iterator i =\n      std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());\n    if (i != piles.end())\n      i->push(x);\n    else\n      piles.push_back(newPile);\n  }\n\n  \n  \n  std::make_heap(piles.begin(), piles.end(), pile_greater<E>());\n  for (Iterator it = first; it != last; it++) {\n    std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());\n    Pile &smallPile = piles.back();\n    *it = smallPile.top();\n    smallPile.pop();\n    if (smallPile.empty())\n      piles.pop_back();\n    else\n      std::push_heap(piles.begin(), piles.end(), pile_greater<E>());\n  }\n  assert(piles.empty());\n}\n\nint main() {\n  int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n  patience_sort(a, a+sizeof(a)/sizeof(*a));\n  std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  return 0;\n}\n", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n"}
{"id": 39821, "name": "Bioinformatics_Sequence mutation", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 39822, "name": "Bioinformatics_Sequence mutation", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 39823, "name": "Tau number", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"The first \" << limit << \" tau numbers are:\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            std::cout << std::setw(6) << n;\n            ++count;\n            if (count % 10 == 0)\n                std::cout << '\\n';\n        }\n    }\n}\n", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n"}
{"id": 39824, "name": "Determinant and permanent", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 39825, "name": "Determinant and permanent", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 39826, "name": "Partition function P", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n"}
{"id": 39827, "name": "Wireworld", "C++": "#include <ggi/ggi.h>\n#include <set>\n#include <map>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <unistd.h> \n\nenum cell_type { none, wire, head, tail };\n\n\n\n\n\n\n\nclass display\n{\npublic:\n  display(int sizex, int sizey, int pixsizex, int pixsizey,\n          ggi_color* colors);\n  ~display()\n  {\n    ggiClose(visual);\n    ggiExit();\n  }\n\n  void flush();\n  bool keypressed() { return ggiKbhit(visual); }\n  void clear();\n  void putpixel(int x, int y, cell_type c);\nprivate:\n  ggi_visual_t visual;\n  int size_x, size_y;\n  int pixel_size_x, pixel_size_y;\n  ggi_pixel pixels[4];\n};\n\ndisplay::display(int sizex, int sizey, int pixsizex, int pixsizey,\n                 ggi_color* colors):\n  pixel_size_x(pixsizex),\n  pixel_size_y(pixsizey)\n{\n  if (ggiInit() < 0)\n  {\n    std::cerr << \"couldn't open ggi\\n\";\n    exit(1);\n  }\n\n  visual = ggiOpen(NULL);\n  if (!visual)\n  {\n    ggiPanic(\"couldn't open visual\\n\");\n  }\n\n  ggi_mode mode;\n  if (ggiCheckGraphMode(visual, sizex, sizey,\n                        GGI_AUTO, GGI_AUTO, GT_4BIT,\n                        &mode) != 0)\n  {\n    if (GT_DEPTH(mode.graphtype) < 2) \n      ggiPanic(\"low-color displays are not supported!\\n\");\n  }\n  if (ggiSetMode(visual, &mode) != 0)\n  {\n    ggiPanic(\"couldn't set graph mode\\n\");\n  }\n  ggiAddFlags(visual, GGIFLAG_ASYNC);\n\n  size_x = mode.virt.x;\n  size_y = mode.virt.y;\n\n  for (int i = 0; i < 4; ++i)\n    pixels[i] = ggiMapColor(visual, colors+i);\n}\n\nvoid display::flush()\n{\n  \n  ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));\n\n  \n  ggiFlush(visual);\n\n  \n  \n  \n  ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));\n}\n\nvoid display::clear()\n{\n  ggiSetGCForeground(visual, pixels[0]);\n  ggiDrawBox(visual, 0, 0, size_x, size_y);\n}\n\nvoid display::putpixel(int x, int y, cell_type cell)\n{\n  \n  \n  ggiSetGCForeground(visual, pixels[cell]);\n  ggiDrawBox(visual,\n             x*pixel_size_x, y*pixel_size_y,\n             pixel_size_x, pixel_size_y);\n}\n\n\n\n\n\n\nclass wireworld\n{\npublic:\n  void set(int posx, int posy, cell_type type);\n  void draw(display& destination);\n  void step();\nprivate:\n  typedef std::pair<int, int> position;\n  typedef std::set<position> position_set;\n  typedef position_set::iterator positer;\n  position_set wires, heads, tails;\n};\n\nvoid wireworld::set(int posx, int posy, cell_type type)\n{\n  position p(posx, posy);\n  wires.erase(p);\n  heads.erase(p);\n  tails.erase(p);\n  switch(type)\n  {\n  case head:\n    heads.insert(p);\n    break;\n  case tail:\n    tails.insert(p);\n    break;\n  case wire:\n    wires.insert(p);\n    break;\n  }\n}\n\nvoid wireworld::draw(display& destination)\n{\n  destination.clear();\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    destination.putpixel(i->first, i->second, head);\n  for (positer i = tails.begin(); i != tails.end(); ++i)\n    destination.putpixel(i->first, i->second, tail);\n  for (positer i = wires.begin(); i != wires.end(); ++i)\n    destination.putpixel(i->first, i->second, wire);\n  destination.flush();\n}\n\nvoid wireworld::step()\n{\n  std::map<position, int> new_heads;\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    for (int dx = -1; dx <= 1; ++dx)\n      for (int dy = -1; dy <= 1; ++dy)\n      {\n        position pos(i->first + dx, i->second + dy);\n        if (wires.count(pos))\n          new_heads[pos]++;\n      }\n  wires.insert(tails.begin(), tails.end());\n  tails.swap(heads);\n  heads.clear();\n  for (std::map<position, int>::iterator i = new_heads.begin();\n       i != new_heads.end();\n       ++i)\n  {\n\n    if (i->second < 3)\n    {\n      wires.erase(i->first);\n      heads.insert(i->first);\n    }\n  }\n}\n\nggi_color colors[4] =\n  {{ 0x0000, 0x0000, 0x0000 },  \n   { 0x8000, 0x8000, 0x8000 },  \n   { 0xffff, 0xffff, 0x0000 },  \n   { 0xffff, 0x0000, 0x0000 }}; \n\nint main(int argc, char* argv[])\n{\n  int display_x = 800;\n  int display_y = 600;\n  int pixel_x = 5;\n  int pixel_y = 5;\n\n  if (argc < 2)\n  {\n    std::cerr << \"No file name given!\\n\";\n    return 1;\n  }\n\n  \n  std::ifstream f(argv[1]);\n  wireworld w;\n  std::string line;\n  int line_number = 0;\n  while (std::getline(f, line))\n  {\n    for (int col = 0; col < line.size(); ++col)\n    {\n      switch (line[col])\n      {\n      case 'h': case 'H':\n        w.set(col, line_number, head);\n        break;\n      case 't': case 'T':\n        w.set(col, line_number, tail);\n        break;\n      case 'w': case 'W': case '.':\n        w.set(col, line_number, wire);\n        break;\n      default:\n        std::cerr << \"unrecognized character: \" << line[col] << \"\\n\";\n        return 1;\n      case ' ':\n        ; \n      }\n    }\n    ++line_number;\n  }\n\n  display d(display_x, display_y, pixel_x, pixel_y, colors);\n\n  w.draw(d);\n\n  while (!d.keypressed())\n  {\n    usleep(100000);\n    w.step();\n    w.draw(d);\n  }\n  std::cout << std::endl;\n}\n", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n"}
{"id": 39828, "name": "Wireworld", "C++": "#include <ggi/ggi.h>\n#include <set>\n#include <map>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <unistd.h> \n\nenum cell_type { none, wire, head, tail };\n\n\n\n\n\n\n\nclass display\n{\npublic:\n  display(int sizex, int sizey, int pixsizex, int pixsizey,\n          ggi_color* colors);\n  ~display()\n  {\n    ggiClose(visual);\n    ggiExit();\n  }\n\n  void flush();\n  bool keypressed() { return ggiKbhit(visual); }\n  void clear();\n  void putpixel(int x, int y, cell_type c);\nprivate:\n  ggi_visual_t visual;\n  int size_x, size_y;\n  int pixel_size_x, pixel_size_y;\n  ggi_pixel pixels[4];\n};\n\ndisplay::display(int sizex, int sizey, int pixsizex, int pixsizey,\n                 ggi_color* colors):\n  pixel_size_x(pixsizex),\n  pixel_size_y(pixsizey)\n{\n  if (ggiInit() < 0)\n  {\n    std::cerr << \"couldn't open ggi\\n\";\n    exit(1);\n  }\n\n  visual = ggiOpen(NULL);\n  if (!visual)\n  {\n    ggiPanic(\"couldn't open visual\\n\");\n  }\n\n  ggi_mode mode;\n  if (ggiCheckGraphMode(visual, sizex, sizey,\n                        GGI_AUTO, GGI_AUTO, GT_4BIT,\n                        &mode) != 0)\n  {\n    if (GT_DEPTH(mode.graphtype) < 2) \n      ggiPanic(\"low-color displays are not supported!\\n\");\n  }\n  if (ggiSetMode(visual, &mode) != 0)\n  {\n    ggiPanic(\"couldn't set graph mode\\n\");\n  }\n  ggiAddFlags(visual, GGIFLAG_ASYNC);\n\n  size_x = mode.virt.x;\n  size_y = mode.virt.y;\n\n  for (int i = 0; i < 4; ++i)\n    pixels[i] = ggiMapColor(visual, colors+i);\n}\n\nvoid display::flush()\n{\n  \n  ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));\n\n  \n  ggiFlush(visual);\n\n  \n  \n  \n  ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));\n}\n\nvoid display::clear()\n{\n  ggiSetGCForeground(visual, pixels[0]);\n  ggiDrawBox(visual, 0, 0, size_x, size_y);\n}\n\nvoid display::putpixel(int x, int y, cell_type cell)\n{\n  \n  \n  ggiSetGCForeground(visual, pixels[cell]);\n  ggiDrawBox(visual,\n             x*pixel_size_x, y*pixel_size_y,\n             pixel_size_x, pixel_size_y);\n}\n\n\n\n\n\n\nclass wireworld\n{\npublic:\n  void set(int posx, int posy, cell_type type);\n  void draw(display& destination);\n  void step();\nprivate:\n  typedef std::pair<int, int> position;\n  typedef std::set<position> position_set;\n  typedef position_set::iterator positer;\n  position_set wires, heads, tails;\n};\n\nvoid wireworld::set(int posx, int posy, cell_type type)\n{\n  position p(posx, posy);\n  wires.erase(p);\n  heads.erase(p);\n  tails.erase(p);\n  switch(type)\n  {\n  case head:\n    heads.insert(p);\n    break;\n  case tail:\n    tails.insert(p);\n    break;\n  case wire:\n    wires.insert(p);\n    break;\n  }\n}\n\nvoid wireworld::draw(display& destination)\n{\n  destination.clear();\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    destination.putpixel(i->first, i->second, head);\n  for (positer i = tails.begin(); i != tails.end(); ++i)\n    destination.putpixel(i->first, i->second, tail);\n  for (positer i = wires.begin(); i != wires.end(); ++i)\n    destination.putpixel(i->first, i->second, wire);\n  destination.flush();\n}\n\nvoid wireworld::step()\n{\n  std::map<position, int> new_heads;\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    for (int dx = -1; dx <= 1; ++dx)\n      for (int dy = -1; dy <= 1; ++dy)\n      {\n        position pos(i->first + dx, i->second + dy);\n        if (wires.count(pos))\n          new_heads[pos]++;\n      }\n  wires.insert(tails.begin(), tails.end());\n  tails.swap(heads);\n  heads.clear();\n  for (std::map<position, int>::iterator i = new_heads.begin();\n       i != new_heads.end();\n       ++i)\n  {\n\n    if (i->second < 3)\n    {\n      wires.erase(i->first);\n      heads.insert(i->first);\n    }\n  }\n}\n\nggi_color colors[4] =\n  {{ 0x0000, 0x0000, 0x0000 },  \n   { 0x8000, 0x8000, 0x8000 },  \n   { 0xffff, 0xffff, 0x0000 },  \n   { 0xffff, 0x0000, 0x0000 }}; \n\nint main(int argc, char* argv[])\n{\n  int display_x = 800;\n  int display_y = 600;\n  int pixel_x = 5;\n  int pixel_y = 5;\n\n  if (argc < 2)\n  {\n    std::cerr << \"No file name given!\\n\";\n    return 1;\n  }\n\n  \n  std::ifstream f(argv[1]);\n  wireworld w;\n  std::string line;\n  int line_number = 0;\n  while (std::getline(f, line))\n  {\n    for (int col = 0; col < line.size(); ++col)\n    {\n      switch (line[col])\n      {\n      case 'h': case 'H':\n        w.set(col, line_number, head);\n        break;\n      case 't': case 'T':\n        w.set(col, line_number, tail);\n        break;\n      case 'w': case 'W': case '.':\n        w.set(col, line_number, wire);\n        break;\n      default:\n        std::cerr << \"unrecognized character: \" << line[col] << \"\\n\";\n        return 1;\n      case ' ':\n        ; \n      }\n    }\n    ++line_number;\n  }\n\n  display d(display_x, display_y, pixel_x, pixel_y, colors);\n\n  w.draw(d);\n\n  while (!d.keypressed())\n  {\n    usleep(100000);\n    w.step();\n    w.draw(d);\n  }\n  std::cout << std::endl;\n}\n", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n"}
{"id": 39829, "name": "Ray-casting algorithm", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nconst double epsilon = numeric_limits<float>().epsilon();\nconst numeric_limits<double> DOUBLE;\nconst double MIN = DOUBLE.min();\nconst double MAX = DOUBLE.max();\n\nstruct Point { const double x, y; };\n\nstruct Edge {\n    const Point a, b;\n\n    bool operator()(const Point& p) const\n    {\n        if (a.y > b.y) return Edge{ b, a }(p);\n        if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });\n        if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;\n        if (p.x < min(a.x, b.x)) return true;\n        auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;\n        auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;\n        return blue >= red;\n    }\n};\n\nstruct Figure {\n    const string  name;\n    const initializer_list<Edge> edges;\n\n    bool contains(const Point& p) const\n    {\n        auto c = 0;\n        for (auto e : edges) if (e(p)) c++;\n        return c % 2 != 0;\n    }\n\n    template<unsigned char W = 3>\n    void check(const initializer_list<Point>& points, ostream& os) const\n    {\n        os << \"Is point inside figure \" << name <<  '?' << endl;\n        for (auto p : points)\n            os << \"  (\" << setw(W) << p.x << ',' << setw(W) << p.y << \"): \" << boolalpha << contains(p) << endl;\n        os << endl;\n    }\n};\n\nint main()\n{\n    const initializer_list<Point> points =  { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };\n    const Figure square = { \"Square\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }\n    };\n\n    const Figure square_hole = { \"Square hole\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},\n           {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure strange = { \"Strange\",\n        {  {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},\n           {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure exagon = { \"Exagon\",\n        {  {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},\n           {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}\n        }\n    };\n\n    for(auto f : {square, square_hole, strange, exagon})\n        f.check(points, cout);\n\n    return EXIT_SUCCESS;\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 39830, "name": "Elliptic curve arithmetic", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 39831, "name": "Elliptic curve arithmetic", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 39832, "name": "Count occurrences of a substring", "C++": "#include <iostream>\n#include <string>\n\n\nint countSubstring(const std::string& str, const std::string& sub)\n{\n    if (sub.length() == 0) return 0;\n    int count = 0;\n    for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n    {\n        ++count;\n    }\n    return count;\n}\n\nint main()\n{\n    std::cout << countSubstring(\"the three truths\", \"th\")    << '\\n';\n    std::cout << countSubstring(\"ababababab\", \"abab\")        << '\\n';\n    std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n    return 0;\n}\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 39833, "name": "Numbers with prime digits whose sum is 13", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 39834, "name": "Numbers with prime digits whose sum is 13", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 39835, "name": "String comparison", "C++": "#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <string>\n\ntemplate <typename T>\nvoid demo_compare(const T &a, const T &b, const std::string &semantically) {\n    std::cout << a << \" and \" << b << \" are \" << ((a == b) ? \"\" : \"not \")\n              << \"exactly \" << semantically << \" equal.\" << std::endl;\n\n    std::cout << a << \" and \" << b << \" are \" << ((a != b) ? \"\" : \"not \")\n              << semantically << \"inequal.\" << std::endl;\n\n    std::cout << a << \" is \" << ((a < b) ? \"\" : \"not \") << semantically\n              << \" ordered before \" << b << '.' << std::endl;\n\n    std::cout << a << \" is \" << ((a > b) ? \"\" : \"not \") << semantically\n              << \" ordered after \" << b << '.' << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n    \n    std::string a((argc > 1) ? argv[1] : \"1.2.Foo\");\n    std::string b((argc > 2) ? argv[2] : \"1.3.Bar\");\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    std::transform(a.begin(), a.end(), a.begin(), ::tolower);\n    std::transform(b.begin(), b.end(), b.begin(), ::tolower);\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    \n    double numA, numB;\n    std::istringstream(a) >> numA;\n    std::istringstream(b) >> numB;\n    demo_compare<double>(numA, numB, \"numerically\");\n    return (a == b);\n}\n", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n"}
{"id": 39836, "name": "Take notes on the command line", "C++": "#include <fstream>\n#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char **argv)\n{\n\tif(argc>1)\n\t{\n\t\tofstream Notes(note_file, ios::app);\n\t\ttime_t timer = time(NULL);\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\tNotes << asctime(localtime(&timer)) << '\\t';\n\t\t\tfor(int i=1;i<argc;i++)\n\t\t\t\tNotes << argv[i] << ' ';\n\t\t\tNotes << endl;\n\t\t\tNotes.close();\n\t\t}\n\t}\n\telse\n\t{\n\t\tifstream Notes(note_file, ios::in);\n\t\tstring line;\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\twhile(!Notes.eof())\n\t\t\t{\n\t\t\t\tgetline(Notes, line);\n\t\t\t\tcout << line << endl;\n\t\t\t}\n\t\t\tNotes.close();\n\t\t}\n\t}\n}\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 39837, "name": "Thiele's interpolation formula", "C++": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string.h>\n\nconstexpr unsigned int N = 32u;\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\nconstexpr unsigned int N2 = N * (N - 1u) / 2u;\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\ndouble ρ(double *x, double *y, double *r, int i, int n) {\n    if (n < 0)\n        return 0;\n    if (!n)\n        return y[i];\n\n    unsigned int idx = (N - 1 - n) * (N - n) / 2 + i;\n    if (r[idx] != r[idx])\n        r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2);\n    return r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, unsigned int n) {\n    return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\ninline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); }\ninline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); }\ninline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); }\n\nint main() {\n    constexpr double step = .05;\n    for (auto i = 0u; i < N; i++) {\n        xval[i] = i * step;\n        t_sin[i] = sin(xval[i]);\n        t_cos[i] = cos(xval[i]);\n        t_tan[i] = t_sin[i] / t_cos[i];\n    }\n    for (auto i = 0u; i < N2; i++)\n        r_sin[i] = r_cos[i] = r_tan[i] = NAN;\n\n    std::cout << std::setw(16) << std::setprecision(25)\n              << 6 * i_sin(.5) << std::endl\n              << 3 * i_cos(.5) << std::endl\n              << 4 * i_tan(1.) << std::endl;\n\n    return 0;\n}\n", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n"}
{"id": 39838, "name": "Fibonacci word", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 39839, "name": "Fibonacci word", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 39840, "name": "Fibonacci word", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 39841, "name": "Angles (geometric), normalization and conversion", "C++": "#include <functional>\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <sstream>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n\ntemplate<typename T>\nT normalize(T a, double b) { return std::fmod(a, b); }\n\ninline double d2d(double a) { return normalize<double>(a, 360); }\ninline double g2g(double a) { return normalize<double>(a, 400); }\ninline double m2m(double a) { return normalize<double>(a, 6400); }\ninline double r2r(double a) { return normalize<double>(a, 2*M_PI); }\n\ndouble d2g(double a) { return g2g(a * 10 / 9); }\ndouble d2m(double a) { return m2m(a * 160 / 9); }\ndouble d2r(double a) { return r2r(a * M_PI / 180); }\ndouble g2d(double a) { return d2d(a * 9 / 10); }\ndouble g2m(double a) { return m2m(a * 16); }\ndouble g2r(double a) { return r2r(a * M_PI / 200); }\ndouble m2d(double a) { return d2d(a * 9 / 160); }\ndouble m2g(double a) { return g2g(a / 16); }\ndouble m2r(double a) { return r2r(a * M_PI / 3200); }\ndouble r2d(double a) { return d2d(a * 180 / M_PI); }\ndouble r2g(double a) { return g2g(a * 200 / M_PI); }\ndouble r2m(double a) { return m2m(a * 3200 / M_PI); }\n\nvoid print(const std::vector<double> &values, const char *s, std::function<double(double)> f) {\n    using namespace std;\n    ostringstream out;\n    out << \"                  ┌───────────────────┐\\n\";\n    out << \"                  │ \" << setw(17) << s << \" │\\n\";\n    out << \"┌─────────────────┼───────────────────┤\\n\";\n    for (double i : values)\n        out << \"│ \" << setw(15) << fixed << i << defaultfloat << \" │ \" << setw(17) << fixed << f(i) << defaultfloat << \" │\\n\";\n    out << \"└─────────────────┴───────────────────┘\\n\";\n    auto str = out.str();\n    boost::algorithm::replace_all(str, \".000000\", \"       \");\n    cout << str;\n}\n\nint main() {\n    std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 };\n    print(values, \"normalized (deg)\", d2d);\n    print(values, \"normalized (grad)\", g2g);\n    print(values, \"normalized (mil)\", m2m);\n    print(values, \"normalized (rad)\", r2r);\n\n    print(values, \"deg -> grad \", d2g);\n    print(values, \"deg -> mil \", d2m);\n    print(values, \"deg -> rad \", d2r);\n\n    print(values, \"grad -> deg \", g2d);\n    print(values, \"grad -> mil \", g2m);\n    print(values, \"grad -> rad \", g2r);\n\n    print(values, \"mil -> deg \", m2d);\n    print(values, \"mil -> grad \", m2g);\n    print(values, \"mil -> rad \", m2r);\n\n    print(values, \"rad -> deg \", r2d);\n    print(values, \"rad -> grad \", r2g);\n    print(values, \"rad -> mil \", r2m);\n\n    return 0;\n}\n", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n"}
{"id": 39842, "name": "Find common directory path", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::string longestPath( const std::vector<std::string> & , char ) ;\n\nint main( ) {\n   std::string dirs[ ] = {\n      \"/home/user1/tmp/coverage/test\" ,\n      \"/home/user1/tmp/covert/operator\" ,\n      \"/home/user1/tmp/coven/members\" } ;\n   std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;\n   std::cout << \"The longest common path of the given directories is \"\n             << longestPath( myDirs , '/' ) << \"!\\n\" ;\n   return 0 ;\n}\n\nstd::string longestPath( const std::vector<std::string> & dirs , char separator ) {\n   std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;\n   int maxCharactersCommon = vsi->length( ) ;\n   std::string compareString = *vsi ;\n   for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {\n      std::pair<std::string::const_iterator , std::string::const_iterator> p = \n\t std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;\n      if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) \n\t maxCharactersCommon = p.first - compareString.begin( ) ;\n   }\n   std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;\n   return compareString.substr( 0 , found ) ;\n}\n", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n"}
{"id": 39843, "name": "Verify distribution uniformity_Naive", "C++": "#include <map>\n#include <iostream>\n#include <cmath>\n\ntemplate<typename F>\n bool test_distribution(F f, int calls, double delta)\n{\n  typedef std::map<int, int> distmap;\n  distmap dist;\n\n  for (int i = 0; i < calls; ++i)\n    ++dist[f()];\n\n  double mean = 1.0/dist.size();\n\n  bool good = true;\n\n  for (distmap::iterator i = dist.begin(); i != dist.end(); ++i)\n  {\n    if (std::abs((1.0 * i->second)/calls - mean) > delta)\n    {\n      std::cout << \"Relative frequency \" << i->second/(1.0*calls)\n                << \" of result \" << i->first\n                << \" deviates by more than \" << delta\n                << \" from the expected value \" << mean << \"\\n\";\n      good = false;\n    }\n  }\n\n  return good;\n}\n", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n"}
{"id": 39844, "name": "Stirling numbers of the second kind", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 39845, "name": "Stirling numbers of the second kind", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 39846, "name": "Recaman's sequence", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 39847, "name": "Recaman's sequence", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 39848, "name": "Memory allocation", "C++": "#include <string>\n\nint main()\n{\n  int* p;\n\n  p = new int;    \n  delete p;       \n\n  p = new int(2); \n  delete p;       \n\n  std::string* p2;\n\n  p2 = new std::string; \n  delete p2;            \n\n  p = new int[10]; \n  delete[] p;      \n\n  p2 = new std::string[10]; \n  delete[] p2;              \n}\n", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n"}
{"id": 39849, "name": "Tic-tac-toe", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum players { Computer, Human, Draw, None };\nconst int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };\n\n\nclass ttt\n{\npublic:\n    ttt() { _p = rand() % 2; reset(); }\n\n    void play()\n    {\n\tint res = Draw;\n\twhile( true )\n\t{\n\t    drawGrid();\n\t    while( true )\n\t    {\n\t\tif( _p ) getHumanMove();\n\t\telse getComputerMove();\n\n\t\tdrawGrid();\n\n\t\tres = checkVictory();\n\t\tif( res != None ) break;\n\n\t\t++_p %= 2;\n\t    }\n\n\t    if( res == Human ) cout << \"CONGRATULATIONS HUMAN --- You won!\";\n\t    else if( res == Computer ) cout << \"NOT SO MUCH A SURPRISE --- I won!\";\n\t    else cout << \"It's a draw!\";\n\n\t    cout << endl << endl;\n\n\t    string r;\n\t    cout << \"Play again( Y / N )? \"; cin >> r;\n\t    if( r != \"Y\" && r != \"y\" ) return;\n\n\t    ++_p %= 2;\n\t    reset();\n\n\t}\n    }\n\nprivate:\n    void reset() \n    {\n\tfor( int x = 0; x < 9; x++ )\n\t    _field[x] = None;\n    }\n\n    void drawGrid()\n    {\n\tsystem( \"cls\" );\n\t\t\n        COORD c = { 0, 2 };\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\n\tcout << \" 1 | 2 | 3 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 4 | 5 | 6 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 7 | 8 | 9 \" << endl << endl << endl;\n\n\tint f = 0;\n\tfor( int y = 0; y < 5; y += 2 )\n\t    for( int x = 1; x < 11; x += 4 )\n\t    {\n\t\tif( _field[f] != None )\n\t\t{\n\t\t    COORD c = { x, 2 + y };\n\t\t    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\t\t    string o = _field[f] == Computer ? \"X\" : \"O\";\n\t\t    cout << o;\n\t\t}\n\t\tf++;\n\t    }\n\n        c.Y = 9;\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n    }\n\n    int checkVictory()\n    {\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    if( _field[iWin[i][0]] != None &&\n\t\t_field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )\n\t    {\n\t\treturn _field[iWin[i][0]];\n\t    }\n\t}\n\n\tint i = 0;\n\tfor( int f = 0; f < 9; f++ )\n\t{\n\t    if( _field[f] != None )\n\t\ti++;\n\t}\n\tif( i == 9 ) return Draw;\n\n\treturn None;\n    }\n\n    void getHumanMove()\n    {\n\tint m;\n\tcout << \"Enter your move ( 1 - 9 ) \";\n\twhile( true )\n\t{\n\t    m = 0;\n\t    do\n\t    { cin >> m; }\n\t    while( m < 1 && m > 9 );\n\n\t    if( _field[m - 1] != None )\n\t\tcout << \"Invalid move. Try again!\" << endl;\n\t    else break;\n\t}\n\n\t_field[m - 1] = Human;\n    }\n\n    void getComputerMove()\n    {\n\tint move = 0;\n\n\tdo{ move = rand() % 9; }\n\twhile( _field[move] != None );\n\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];\n\n\t    if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )\n\t    {\n\t\tmove = try3;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) \n\t    {\t\t\t\n\t\tmove = try2;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )\n\t    {\n\t\tmove = try1;\n\t\tif( _field[try2] == Computer ) break;\n\t    }\n        }\n\t_field[move] = Computer;\n\t\t\n    }\n\n\nint _p;\nint _field[9];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n\n    ttt tic;\n    tic.play();\n\n    return 0;\n}\n\n", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n"}
{"id": 39850, "name": "Integer sequence", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 39851, "name": "Integer sequence", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 39852, "name": "Integer sequence", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 39853, "name": "Entropy_Narcissist", "C++": "#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\n\nstring readFile (string path) {\n    string contents;\n    string line;\n    ifstream inFile(path);\n    while (getline (inFile, line)) {\n        contents.append(line);\n        contents.append(\"\\n\");\n    }\n    inFile.close();\n    return contents;\n}\n\ndouble entropy (string X) {\n    const int MAXCHAR = 127;\n    int N = X.length();\n    int count[MAXCHAR];\n    double count_i;\n    char ch;\n    double sum = 0.0;\n    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;\n    for (int pos = 0; pos < N; pos++) {\n        ch = X[pos];\n        count[(int)ch]++;\n    }\n    for (int n_i = 0; n_i < MAXCHAR; n_i++) {\n        count_i = count[n_i];\n        if (count_i > 0) sum -= count_i / N * log2(count_i / N);\n    }\n    return sum;\n}\n\nint main () {\n    cout<<entropy(readFile(\"entropy.cpp\"));\n    return 0;\n}\n", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n"}
{"id": 39854, "name": "Bitwise operations", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n"}
{"id": 39855, "name": "Dragon curve", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n"}
{"id": 39856, "name": "Read a file line by line", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n"}
{"id": 39857, "name": "Doubly-linked list_Element insertion", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n"}
{"id": 39858, "name": "Quickselect algorithm", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 39859, "name": "Quickselect algorithm", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 39860, "name": "Non-decimal radices_Convert", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 39861, "name": "Walk a directory_Recursively", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 39862, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 39863, "name": "Classes", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n"}
{"id": 39864, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 39865, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 39866, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 39867, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 39868, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 39869, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n"}
{"id": 39870, "name": "Create a file", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n"}
{"id": 39871, "name": "Delegates", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 39872, "name": "Delegates", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 39873, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "C#": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 39874, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 39875, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "C#": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 39876, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "C#": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 39877, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n"}
{"id": 39878, "name": "Faulhaber's triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 39879, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 39880, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 39881, "name": "Array concatenation", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 39882, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n"}
{"id": 39883, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 39884, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 39885, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 39886, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 39887, "name": "First-class functions", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n"}
{"id": 39888, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 39889, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 39890, "name": "XML_Output", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n"}
{"id": 39891, "name": "Regular expressions", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n"}
{"id": 39892, "name": "Guess the number_With feedback (player)", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n"}
{"id": 39893, "name": "Guess the number_With feedback (player)", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n"}
{"id": 39894, "name": "Hash from two arrays", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n"}
{"id": 39895, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 39896, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 39897, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 39898, "name": "Animate a pendulum", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n"}
{"id": 39899, "name": "Animate a pendulum", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n"}
{"id": 39900, "name": "Sorting algorithms_Heapsort", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n"}
{"id": 39901, "name": "Playing cards", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 39902, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 39903, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 39904, "name": "Sierpinski carpet", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n"}
{"id": 39905, "name": "Sorting algorithms_Bogosort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 39906, "name": "Merge and aggregate datasets", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n"}
{"id": 39907, "name": "Euler method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 39908, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 39909, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 39910, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 39911, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 39912, "name": "JortSort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n"}
{"id": 39913, "name": "Leap year", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n"}
{"id": 39914, "name": "Sort numbers lexicographically", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n"}
{"id": 39915, "name": "Number names", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n"}
{"id": 39916, "name": "Compare length of two strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n"}
{"id": 39917, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 39918, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 39919, "name": "Increment a numerical string", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 39920, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 39921, "name": "Averages_Arithmetic mean", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n"}
{"id": 39922, "name": "Entropy", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n"}
{"id": 39923, "name": "Tokenize a string with escaping", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n"}
{"id": 39924, "name": "Hello world_Text", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 39925, "name": "Forward difference", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 39926, "name": "Primality by trial division", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 39927, "name": "Primality by trial division", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 39928, "name": "Evaluate binomial coefficients", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 39929, "name": "Collections", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 39930, "name": "Collections", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 39931, "name": "Singly-linked list_Traversal", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n"}
{"id": 39932, "name": "Bitmap_Write a PPM file", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 39933, "name": "Bitmap_Write a PPM file", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 39934, "name": "Delete a file", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n"}
{"id": 39935, "name": "Discordian date", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n"}
{"id": 39936, "name": "Discordian date", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n"}
{"id": 39937, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 39938, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n"}
{"id": 39939, "name": "Dragon curve", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n"}
{"id": 39940, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n"}
{"id": 39941, "name": "Doubly-linked list_Element insertion", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n"}
{"id": 39942, "name": "Quickselect algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n"}
{"id": 39943, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 39944, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n"}
{"id": 39945, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 39946, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 39947, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 39948, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 39949, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 39950, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 39951, "name": "LZW compression", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n"}
{"id": 39952, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 39953, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 39954, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 39955, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 39956, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 39957, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 39958, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n"}
{"id": 39959, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 39960, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 39961, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 39962, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 39963, "name": "Longest string challenge", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n"}
{"id": 39964, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 39965, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 39966, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 39967, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 39968, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 39969, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 39970, "name": "Dining philosophers", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n"}
{"id": 39971, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 39972, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 39973, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 39974, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 39975, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 39976, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 39977, "name": "Spiral matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n"}
{"id": 39978, "name": "Optional parameters", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n"}
{"id": 39979, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n"}
{"id": 39980, "name": "Faulhaber's triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 39981, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 39982, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 39983, "name": "Word wheel", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n"}
{"id": 39984, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 39985, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 39986, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 39987, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 39988, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 39989, "name": "Primes - allocate descendants to their ancestors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n"}
{"id": 39990, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 39991, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 39992, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n"}
{"id": 39993, "name": "XML_Output", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n"}
{"id": 39994, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 39995, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 39996, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 39997, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 39998, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n"}
{"id": 39999, "name": "Colour pinstripe_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n"}
{"id": 40000, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n"}
{"id": 40001, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n"}
{"id": 40002, "name": "Animate a pendulum", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n"}
{"id": 40003, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 40004, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 40005, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 40006, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 40007, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "VB": "Option Base {0|1}\n"}
{"id": 40008, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 40009, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n"}
{"id": 40010, "name": "Euler method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n"}
{"id": 40011, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 40012, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 40013, "name": "JortSort", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n"}
{"id": 40014, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n"}
{"id": 40015, "name": "Combinations and permutations", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n"}
{"id": 40016, "name": "Sort numbers lexicographically", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n"}
{"id": 40017, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n"}
{"id": 40018, "name": "Sorting algorithms_Shell sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n"}
{"id": 40019, "name": "Doubly-linked list_Definition", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n"}
{"id": 40020, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n"}
{"id": 40021, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 40022, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 40023, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n"}
{"id": 40024, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40025, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40026, "name": "Tokenize a string with escaping", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n"}
{"id": 40027, "name": "Tokenize a string with escaping", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n"}
{"id": 40028, "name": "Hello world_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n"}
{"id": 40029, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n"}
{"id": 40030, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n"}
{"id": 40031, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 40032, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 40033, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n"}
{"id": 40034, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n"}
{"id": 40035, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n"}
{"id": 40036, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n"}
{"id": 40037, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 40038, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 40039, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n"}
{"id": 40040, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n"}
{"id": 40041, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n"}
{"id": 40042, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "VB": "Imports System.Math\n\nModule RayCasting\n\n    Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}\n    Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}\n    Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}\n    Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}\n    Private shapes As Integer()()() = {square, squareHole, strange, hexagon}\n\n    Public Sub Main()\n        Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}\n\n        For Each shape As Integer()() In shapes\n            For Each point As Double() In testPoints\n                Console.Write(String.Format(\"{0} \", Contains(shape, point).ToString.PadLeft(7)))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\n    Private Function Contains(shape As Integer()(), point As Double()) As Boolean\n\n        Dim inside As Boolean = False\n        Dim length As Integer = shape.Length\n\n        For i As Integer = 0 To length - 1\n            If Intersects(shape(i), shape((i + 1) Mod length), point) Then\n                inside = Not inside\n            End If\n        Next\n\n        Return inside\n    End Function\n\n    Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean\n\n        If a(1) > b(1) Then Return Intersects(b, a, p)\n        If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001\n        If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False\n        If p(0) < Min(a(0), b(0)) Then Return True\n        Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))\n        Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))\n\n        Return red >= blue\n    End Function\nEnd Module\n"}
{"id": 40043, "name": "Count occurrences of a substring", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n", "VB": "Function CountSubstring(str,substr)\n\tCountSubstring = 0\n\tFor i = 1 To Len(str)\n\t\tIf Len(str) >= Len(substr) Then\n\t\t\tIf InStr(i,str,substr) Then\n\t\t\t\tCountSubstring = CountSubstring + 1\n\t\t\t\ti = InStr(i,str,substr) + Len(substr) - 1\n\t\t\tEnd If\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write CountSubstring(\"the three truths\",\"th\") & vbCrLf\nWScript.StdOut.Write CountSubstring(\"ababababab\",\"abab\") & vbCrLf\n"}
{"id": 40044, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40045, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40046, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "VB": "Imports System.IO\n\nModule Notes\n    Function Main(ByVal cmdArgs() As String) As Integer\n        Try\n            If cmdArgs.Length = 0 Then\n                Using sr As New StreamReader(\"NOTES.TXT\")\n                    Console.WriteLine(sr.ReadToEnd)\n                End Using\n            Else\n                Using sw As New StreamWriter(\"NOTES.TXT\", True)\n                    sw.WriteLine(Date.Now.ToString())\n                    sw.WriteLine(\"{0}{1}\", ControlChars.Tab, String.Join(\" \", cmdArgs))\n                End Using\n            End If\n        Catch\n        End Try\n    End Function\nEnd Module\n"}
{"id": 40047, "name": "Find common directory path", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n", "VB": "Public Function CommonDirectoryPath(ParamArray Paths()) As String\nDim v As Variant\nDim Path() As String, s As String\nDim i As Long, j As Long, k As Long\nConst PATH_SEPARATOR As String = \"/\"\n  \n  For Each v In Paths\n    ReDim Preserve Path(0 To i)\n    Path(i) = v\n    i = i + 1\n  Next v\n  \n  k = 1\n  \n  Do\n    For i = 0 To UBound(Path)\n      If i Then\n        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then\n          Exit Do\n        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then\n          Exit Do\n        End If\n      Else\n        j = InStr(k, Path(i), PATH_SEPARATOR)\n        If j = 0 Then\n          Exit Do\n        End If\n      End If\n    Next i\n    s = Left$(Path(0), j + CLng(k <> 1))\n    k = j + 1\n  Loop\n  CommonDirectoryPath = s\n  \nEnd Function\n\nSub Main()\n\n\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/home/user1/tmp\"\n \n Debug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\", _\n \"/home/user1/abc/coven/members\") = _\n \"/home/user1\"\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/hope/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/\"\n\nEnd Sub\n"}
{"id": 40048, "name": "Verify distribution uniformity_Naive", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "VB": "Option Explicit\n\nsub verifydistribution(calledfunction, samples, delta)\n\tDim i, n, maxdiff\n\t\n\tDim d : Set d = CreateObject(\"Scripting.Dictionary\")\n\twscript.echo \"Running \"\"\" & calledfunction & \"\"\" \" & samples & \" times...\"\n\tfor i = 1 to samples\n\t\tExecute \"n = \" & calledfunction\n\t\td(n) = d(n) + 1\n\tnext\n\tn = d.Count\n\tmaxdiff = 0\n\twscript.echo \"Expected average count is \" & Int(samples/n) & \" across \" & n & \" buckets.\"\n\tfor each i in d.Keys\n\t\tdim diff : diff = abs(1 - d(i) / (samples/n))\n\t\tif diff > maxdiff then maxdiff = diff\n\t\twscript.echo \"Bucket \" & i & \" had \" & d(i) & \" occurences\" _\n\t\t& vbTab & \" difference from expected=\" & FormatPercent(diff, 2)\n\tnext\n\twscript.echo \"Maximum found variation is \" & FormatPercent(maxdiff, 2) _\n\t\t& \", desired limit is \" & FormatPercent(delta, 2) & \".\"\n\tif maxdiff > delta then wscript.echo \"Skewed!\" else wscript.echo \"Smooth!\"\nend sub\n"}
{"id": 40049, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    Class Sterling\n        Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)\n\n        Private Shared Function CacheKey(n As Integer, k As Integer) As String\n            Return String.Format(\"{0}:{1}\", n, k)\n        End Function\n\n        Private Shared Function Impl(n As Integer, k As Integer) As BigInteger\n            If n = 0 AndAlso k = 0 Then\n                Return 1\n            End If\n            If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then\n                Return 0\n            End If\n            If n = k Then\n                Return 1\n            End If\n            If k > n Then\n                Return 0\n            End If\n\n            Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)\n        End Function\n\n        Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger\n            Dim key = CacheKey(n, k)\n            If COMPUTED.ContainsKey(key) Then\n                Return COMPUTED(key)\n            End If\n\n            Dim result = Impl(n, k)\n            COMPUTED.Add(key, result)\n            Return result\n        End Function\n    End Class\n\n    Sub Main()\n        Console.WriteLine(\"Stirling numbers of the second kind:\")\n        Dim max = 12\n        Console.Write(\"n/k\")\n        For n = 0 To max\n            Console.Write(\"{0,10}\", n)\n        Next\n        Console.WriteLine()\n        For n = 0 To max\n            Console.Write(\"{0,3}\", n)\n            For k = 0 To n\n                Console.Write(\"{0,10}\", Sterling.Sterling2(n, k))\n            Next\n            Console.WriteLine()\n        Next\n        Console.WriteLine(\"The maximum value of S2(100, k) = \")\n        Dim previous = BigInteger.Zero\n        For k = 1 To 100\n            Dim current = Sterling.Sterling2(100, k)\n            If current > previous Then\n                previous = current\n            Else\n                Console.WriteLine(previous)\n                Console.WriteLine(\"({0} digits, k = {1})\", previous.ToString().Length, k - 1)\n                Exit For\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40050, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "VB": "Imports System.Numerics\n\nModule Module1\n\n    Class Sterling\n        Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)\n\n        Private Shared Function CacheKey(n As Integer, k As Integer) As String\n            Return String.Format(\"{0}:{1}\", n, k)\n        End Function\n\n        Private Shared Function Impl(n As Integer, k As Integer) As BigInteger\n            If n = 0 AndAlso k = 0 Then\n                Return 1\n            End If\n            If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then\n                Return 0\n            End If\n            If n = k Then\n                Return 1\n            End If\n            If k > n Then\n                Return 0\n            End If\n\n            Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)\n        End Function\n\n        Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger\n            Dim key = CacheKey(n, k)\n            If COMPUTED.ContainsKey(key) Then\n                Return COMPUTED(key)\n            End If\n\n            Dim result = Impl(n, k)\n            COMPUTED.Add(key, result)\n            Return result\n        End Function\n    End Class\n\n    Sub Main()\n        Console.WriteLine(\"Stirling numbers of the second kind:\")\n        Dim max = 12\n        Console.Write(\"n/k\")\n        For n = 0 To max\n            Console.Write(\"{0,10}\", n)\n        Next\n        Console.WriteLine()\n        For n = 0 To max\n            Console.Write(\"{0,3}\", n)\n            For k = 0 To n\n                Console.Write(\"{0,10}\", Sterling.Sterling2(n, k))\n            Next\n            Console.WriteLine()\n        Next\n        Console.WriteLine(\"The maximum value of S2(100, k) = \")\n        Dim previous = BigInteger.Zero\n        For k = 1 To 100\n            Dim current = Sterling.Sterling2(100, k)\n            If current > previous Then\n                previous = current\n            Else\n                Console.WriteLine(previous)\n                Console.WriteLine(\"({0} digits, k = {1})\", previous.ToString().Length, k - 1)\n                Exit For\n            End If\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40051, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n"}
{"id": 40052, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n"}
{"id": 40053, "name": "Tic-tac-toe", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n", "VB": "Option Explicit\n\nPrivate Lines(1 To 3, 1 To 3) As String\nPrivate Nb As Byte, player As Byte\nPrivate GameWin As Boolean, GameOver As Boolean\n\nSub Main_TicTacToe()\nDim p As String\n\n    InitLines\n    printLines Nb\n    Do\n        p = WhoPlay\n        Debug.Print p & \" play\"\n        If p = \"Human\" Then\n            Call HumanPlay\n            GameWin = IsWinner(\"X\")\n        Else\n            Call ComputerPlay\n            GameWin = IsWinner(\"O\")\n        End If\n        If Not GameWin Then GameOver = IsEnd\n    Loop Until GameWin Or GameOver\n    If Not GameOver Then\n        Debug.Print p & \" Win !\"\n    Else\n        Debug.Print \"Game Over!\"\n    End If\nEnd Sub\n\nSub InitLines(Optional S As String)\nDim i As Byte, j As Byte\n    Nb = 0: player = 0\n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            Lines(i, j) = \"#\"\n        Next j\n    Next i\nEnd Sub\n\nSub printLines(Nb As Byte)\nDim i As Byte, j As Byte, strT As String\n    Debug.Print \"Loop \" & Nb\n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            strT = strT & Lines(i, j)\n        Next j\n        Debug.Print strT\n        strT = vbNullString\n    Next i\nEnd Sub\n\nFunction WhoPlay(Optional S As String) As String\n    If player = 0 Then\n        player = 1\n        WhoPlay = \"Human\"\n    Else\n        player = 0\n        WhoPlay = \"Computer\"\n    End If\nEnd Function\n\nSub HumanPlay(Optional S As String)\nDim L As Byte, C As Byte, GoodPlay As Boolean\n\n    Do\n        L = Application.InputBox(\"Choose the row\", \"Numeric only\", Type:=1)\n        If L > 0 And L < 4 Then\n            C = Application.InputBox(\"Choose the column\", \"Numeric only\", Type:=1)\n            If C > 0 And C < 4 Then\n                If Lines(L, C) = \"#\" And Not Lines(L, C) = \"X\" And Not Lines(L, C) = \"O\" Then\n                    Lines(L, C) = \"X\"\n                    Nb = Nb + 1\n                    printLines Nb\n                    GoodPlay = True\n                End If\n            End If\n        End If\n    Loop Until GoodPlay\nEnd Sub\n\nSub ComputerPlay(Optional S As String)\nDim L As Byte, C As Byte, GoodPlay As Boolean\n\n    Randomize Timer\n    Do\n        L = Int((Rnd * 3) + 1)\n        C = Int((Rnd * 3) + 1)\n        If Lines(L, C) = \"#\" And Not Lines(L, C) = \"X\" And Not Lines(L, C) = \"O\" Then\n            Lines(L, C) = \"O\"\n            Nb = Nb + 1\n            printLines Nb\n            GoodPlay = True\n        End If\n    Loop Until GoodPlay\nEnd Sub\n\nFunction IsWinner(S As String) As Boolean\nDim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String\n\n    Ch = String(UBound(Lines, 1), S)\n    \n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            strTL = strTL & Lines(i, j)\n            strTC = strTC & Lines(j, i)\n        Next j\n        If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For\n        strTL = vbNullString: strTC = vbNullString\n    Next i\n    \n    strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3)\n    strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1)\n    If strTL = Ch Or strTC = Ch Then IsWinner = True\nEnd Function\n\nFunction IsEnd() As Boolean\nDim i As Byte, j As Byte\n\n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            If Lines(i, j) = \"#\" Then Exit Function\n        Next j\n    Next i\n    IsEnd = True\nEnd Function\n"}
{"id": 40054, "name": "Bitwise operations", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 40055, "name": "Dragon curve", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n"}
{"id": 40056, "name": "Read a file line by line", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 40057, "name": "Doubly-linked list_Element insertion", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n"}
{"id": 40058, "name": "Smarandache prime-digital sequence", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n"}
{"id": 40059, "name": "Quickselect algorithm", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n"}
{"id": 40060, "name": "Quickselect algorithm", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n"}
{"id": 40061, "name": "Non-decimal radices_Convert", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 40062, "name": "Walk a directory_Recursively", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 40063, "name": "Main step of GOST 28147-89", "C++": "UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)\n{\n    UINT_64 N;\n\tN = N1;\n\tN = (N<<32)|N2;\n\treturn UINT_64(N);\n}\n\nUINT_32 TGost::ReplaceBlock(UINT_32 x)\n{   \n    register i;\n    UINT_32 res = 0UL;\n    for(i=7;i>=0;i--)\n    {\n       ui4_0 = x>>(i*4);\n       ui4_0 = BS[ui4_0][i];\n       res = (res<<4)|ui4_0;\n    }\n    return res;\n}\n\nUINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)\n{\n   UINT_32 N1,N2,S=0UL;\n   N1=UINT_32(N);\n   N2=N>>32;\n   S = N1 + X % 0x4000000000000;\n   S = ReplaceBlock(S);\n   S = (S<<11)|(S>>21);\n   S ^= N2;\n   N2 = N1;\n   N1 = S;\n   return SWAP32(N2,N1);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype sBox [8][16]byte\n\ntype gost struct {\n    k87, k65, k43, k21 [256]byte\n    enc                []byte\n}\n\nfunc newGost(s *sBox) *gost {\n    var g gost\n    for i := range g.k87 {\n        g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]\n        g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]\n        g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]\n        g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]\n    }\n    g.enc = make([]byte, 8)\n    return &g\n}\n\nfunc (g *gost) f(x uint32) uint32 {\n    x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |\n        uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])\n    return x<<11 | x>>(32-11)\n}\n\n\n\n\n\n\nvar cbrf = sBox{\n    {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},\n    {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},\n    {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},\n    {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},\n    {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},\n    {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},\n    {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},\n    {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},\n}\n\nfunc u32(b []byte) uint32 {\n    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc b4(u uint32, b []byte) {\n    b[0] = byte(u)\n    b[1] = byte(u >> 8)\n    b[2] = byte(u >> 16)\n    b[3] = byte(u >> 24)\n}\n\nfunc (g *gost) mainStep(input []byte, key []byte) {\n    key32 := u32(key)\n    input1 := u32(input[:4])\n    input2 := u32(input[4:])\n    b4(g.f(key32+input1)^input2, g.enc[:4])\n    copy(g.enc[4:], input[:4])\n}\n\nfunc main() {\n    input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}\n    key := []byte{0xF9, 0x04, 0xC1, 0xE2}\n\n    g := newGost(&cbrf)\n    g.mainStep(input, key)\n    for _, b := range g.enc {\n        fmt.Printf(\"[%02x]\", b)\n    }\n    fmt.Println()\n}\n"}
{"id": 40064, "name": "State name puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n"}
{"id": 40065, "name": "CRC-32", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 40066, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 40067, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 40068, "name": "Classes", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 40069, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 40070, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 40071, "name": "LZW compression", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n"}
{"id": 40072, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 40073, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 40074, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 40075, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 40076, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 40077, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 40078, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 40079, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 40080, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 40081, "name": "Mertens function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n"}
{"id": 40082, "name": "Order by pair comparisons", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n"}
{"id": 40083, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 40084, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 40085, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 40086, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 40087, "name": "Anonymous recursion", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 40088, "name": "Snake", "C++": "#include <windows.h>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nconst int WID = 60, HEI = 30, MAX_LEN = 600;\nenum DIR { NORTH, EAST, SOUTH, WEST };\n\nclass snake {\npublic:\n    snake() {\n        console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( \"Snake\" ); \n        COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );\n        SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );\n        CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );\n    }\n    void play() {\n        std::string a;\n        while( 1 ) {\n            createField(); alive = true;\n            while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }\n            COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );\n            SetConsoleTextAttribute( console, 0x000b );\n            std::cout << \"Play again [Y/N]? \"; std::cin >> a;\n            if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;\n        }\n    }\nprivate:\n    void createField() {\n        COORD coord = { 0, 0 }; DWORD c;\n        FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );\n        FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );\n        SetConsoleCursorPosition( console, coord );\n        int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;\n        for( x = 0; x < WID; x++ ) {\n            brd[x] = brd[x + WID * ( HEI - 1 )] = '+';\n        }\n        for( ; y < HEI; y++ ) {\n            brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';\n        }\n        do {\n            x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n        } while( brd[x + WID * y] );\n        brd[x + WID * y] = '@';\n        tailIdx = 0; headIdx = 4; x = 3; y = 2;\n        for( int c = tailIdx; c < headIdx; c++ ) {\n            brd[x + WID * y] = '#';\n            snk[c].X = 3 + c; snk[c].Y = 2;\n        }\n        head = snk[3]; dir = EAST; points = 0;\n    }\n    void readKey() {\n        if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;\n        if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;\n        if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;\n        if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;\n    }\n    void drawField() {\n        COORD coord; char t;\n        for( int y = 0; y < HEI; y++ ) {\n            coord.Y = y;\n            for( int x = 0; x < WID; x++ ) {\n                t = brd[x + WID * y]; if( !t ) continue;\n                coord.X = x; SetConsoleCursorPosition( console, coord );\n                if( coord.X == head.X && coord.Y == head.Y ) {\n                    SetConsoleTextAttribute( console, 0x002e );\n                    std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );\n                    continue;\n                }\n                switch( t ) {\n                    case '#': SetConsoleTextAttribute( console, 0x002a ); break;\n                    case '+': SetConsoleTextAttribute( console, 0x0019 ); break;\n                    case '@': SetConsoleTextAttribute( console, 0x004c ); break;\n                }\n                std::cout << t; SetConsoleTextAttribute( console, 0x0000 );\n            }\n        }\n        std::cout << t; SetConsoleTextAttribute( console, 0x0007 );\n        COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );\n        std::cout << \"Points: \" << points;\n    }\n    void moveSnake() {\n        switch( dir ) {\n            case NORTH: head.Y--; break;\n            case EAST: head.X++; break;\n            case SOUTH: head.Y++; break;\n            case WEST: head.X--; break;\n        }\n        char t = brd[head.X + WID * head.Y];\n        if( t && t != '@' ) { alive = false; return; }\n        brd[head.X + WID * head.Y] = '#';\n        snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;\n        if( ++headIdx >= MAX_LEN ) headIdx = 0;\n        if( t == '@' ) {\n            points++; int x, y;\n            do {\n                x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n            } while( brd[x + WID * y] );\n            brd[x + WID * y] = '@'; return;\n        }\n        SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';\n        brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;\n        if( ++tailIdx >= MAX_LEN ) tailIdx = 0;\n    }\n    bool alive; char brd[WID * HEI]; \n    HANDLE console; DIR dir; COORD snk[MAX_LEN];\n    COORD head; int tailIdx, headIdx, points;\n};\nint main( int argc, char* argv[] ) {\n    srand( static_cast<unsigned>( time( NULL ) ) );\n    snake s; s.play(); return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"time\"\n\n\ttermbox \"github.com/nsf/termbox-go\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano())\n\tscore, err := playSnake()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Final score:\", score)\n}\n\ntype snake struct {\n\tbody          []position \n\theading       direction\n\twidth, height int\n\tcells         []termbox.Cell\n}\n\ntype position struct {\n\tX int\n\tY int\n}\n\ntype direction int\n\nconst (\n\tNorth direction = iota\n\tEast\n\tSouth\n\tWest\n)\n\nfunc (p position) next(d direction) position {\n\tswitch d {\n\tcase North:\n\t\tp.Y--\n\tcase East:\n\t\tp.X++\n\tcase South:\n\t\tp.Y++\n\tcase West:\n\t\tp.X--\n\t}\n\treturn p\n}\n\nfunc playSnake() (int, error) {\n\terr := termbox.Init()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer termbox.Close()\n\n\ttermbox.Clear(fg, bg)\n\ttermbox.HideCursor()\n\ts := &snake{\n\t\t\n\t\t\n\t\tbody:  make([]position, 0, 32),\n\t\tcells: termbox.CellBuffer(),\n\t}\n\ts.width, s.height = termbox.Size()\n\ts.drawBorder()\n\ts.startSnake()\n\ts.placeFood()\n\ts.flush()\n\n\tmoveCh, errCh := s.startEventLoop()\n\tconst delay = 125 * time.Millisecond\n\tfor t := time.NewTimer(delay); ; t.Reset(delay) {\n\t\tvar move direction\n\t\tselect {\n\t\tcase err = <-errCh:\n\t\t\treturn len(s.body), err\n\t\tcase move = <-moveCh:\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C \n\t\t\t}\n\t\tcase <-t.C:\n\t\t\tmove = s.heading\n\t\t}\n\t\tif s.doMove(move) {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn len(s.body), err\n}\n\nfunc (s *snake) startEventLoop() (<-chan direction, <-chan error) {\n\tmoveCh := make(chan direction)\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(errCh)\n\t\tfor {\n\t\t\tswitch ev := termbox.PollEvent(); ev.Type {\n\t\t\tcase termbox.EventKey:\n\t\t\t\tswitch ev.Ch { \n\t\t\t\tcase 'w', 'W', 'k', 'K':\n\t\t\t\t\tmoveCh <- North\n\t\t\t\tcase 'a', 'A', 'h', 'H':\n\t\t\t\t\tmoveCh <- West\n\t\t\t\tcase 's', 'S', 'j', 'J':\n\t\t\t\t\tmoveCh <- South\n\t\t\t\tcase 'd', 'D', 'l', 'L':\n\t\t\t\t\tmoveCh <- East\n\t\t\t\tcase 0:\n\t\t\t\t\tswitch ev.Key { \n\t\t\t\t\tcase termbox.KeyArrowUp:\n\t\t\t\t\t\tmoveCh <- North\n\t\t\t\t\tcase termbox.KeyArrowDown:\n\t\t\t\t\t\tmoveCh <- South\n\t\t\t\t\tcase termbox.KeyArrowLeft:\n\t\t\t\t\t\tmoveCh <- West\n\t\t\t\t\tcase termbox.KeyArrowRight:\n\t\t\t\t\t\tmoveCh <- East\n\t\t\t\t\tcase termbox.KeyEsc: \n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase termbox.EventResize:\n\t\t\t\t\n\t\t\t\terrCh <- errors.New(\"terminal resizing unsupported\")\n\t\t\t\treturn\n\t\t\tcase termbox.EventError:\n\t\t\t\terrCh <- ev.Err\n\t\t\t\treturn\n\t\t\tcase termbox.EventInterrupt:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn moveCh, errCh\n}\n\nfunc (s *snake) flush() {\n\ttermbox.Flush()\n\ts.cells = termbox.CellBuffer()\n}\n\nfunc (s *snake) getCellRune(p position) rune {\n\ti := p.Y*s.width + p.X\n\treturn s.cells[i].Ch\n}\nfunc (s *snake) setCell(p position, c termbox.Cell) {\n\ti := p.Y*s.width + p.X\n\ts.cells[i] = c\n}\n\nfunc (s *snake) drawBorder() {\n\tfor x := 0; x < s.width; x++ {\n\t\ts.setCell(position{x, 0}, border)\n\t\ts.setCell(position{x, s.height - 1}, border)\n\t}\n\tfor y := 0; y < s.height-1; y++ {\n\t\ts.setCell(position{0, y}, border)\n\t\ts.setCell(position{s.width - 1, y}, border)\n\t}\n}\n\nfunc (s *snake) placeFood() {\n\tfor {\n\t\t\n\t\tx := rand.Intn(s.width-2) + 1\n\t\ty := rand.Intn(s.height-2) + 1\n\t\tfoodp := position{x, y}\n\t\tr := s.getCellRune(foodp)\n\t\tif r != ' ' {\n\t\t\tcontinue\n\t\t}\n\t\ts.setCell(foodp, food)\n\t\treturn\n\t}\n}\n\nfunc (s *snake) startSnake() {\n\t\n\tx := rand.Intn(s.width/2) + s.width/4\n\ty := rand.Intn(s.height/2) + s.height/4\n\thead := position{x, y}\n\ts.setCell(head, snakeHead)\n\ts.body = append(s.body[:0], head)\n\ts.heading = direction(rand.Intn(4))\n}\n\nfunc (s *snake) doMove(move direction) bool {\n\thead := s.body[len(s.body)-1]\n\ts.setCell(head, snakeBody)\n\thead = head.next(move)\n\ts.heading = move\n\ts.body = append(s.body, head)\n\tr := s.getCellRune(head)\n\ts.setCell(head, snakeHead)\n\tgameOver := false\n\tswitch r {\n\tcase food.Ch:\n\t\ts.placeFood()\n\tcase border.Ch, snakeBody.Ch:\n\t\tgameOver = true\n\t\tfallthrough\n\tcase empty.Ch:\n\t\ts.setCell(s.body[0], empty)\n\t\ts.body = s.body[1:]\n\tdefault:\n\t\tpanic(r)\n\t}\n\ts.flush()\n\treturn gameOver\n}\n\nconst (\n\tfg = termbox.ColorWhite\n\tbg = termbox.ColorBlack\n)\n\n\n\nvar (\n\tempty     = termbox.Cell{Ch: ' ', Bg: bg, Fg: fg}\n\tborder    = termbox.Cell{Ch: '+', Bg: bg, Fg: termbox.ColorBlue}\n\tsnakeBody = termbox.Cell{Ch: '#', Bg: bg, Fg: termbox.ColorGreen}\n\tsnakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold}\n\tfood      = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed}\n)\n"}
{"id": 40089, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 40090, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 40091, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 40092, "name": "Legendre prime counting function", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n"}
{"id": 40093, "name": "Use another language to call a function", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n"}
{"id": 40094, "name": "Longest string challenge", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n"}
{"id": 40095, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 40096, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 40097, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 40098, "name": "Unprimeable numbers", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n"}
{"id": 40099, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 40100, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 40101, "name": "Chernick's Carmichael numbers", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n"}
{"id": 40102, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 40103, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 40104, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 40105, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 40106, "name": "Create an object at a given address", "C++": "#include <string>\n#include <iostream>\n\nint main()\n{\n    \n    char* data = new char[sizeof(std::string)];\n\n    \n    std::string* stringPtr = new (data) std::string(\"ABCD\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    \n    stringPtr->~basic_string();\n    stringPtr = new (data) std::string(\"123456\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    stringPtr->~basic_string();\n    delete[] data;\n}\n", "Go": "package main\n\nimport(\n\t\"fmt\"\n\t\"unsafe\"\n\t\"reflect\"\n)\n\nfunc pointer() {\n\tfmt.Printf(\"Pointer:\\n\")\n\n\t\n\t\n\t\n\t\n\tvar i int\n\tp := &i\n\n\tfmt.Printf(\"Before:\\n\\t%v: %v, %v\\n\", p, *p, i)\n\n\t*p = 3\n\n\tfmt.Printf(\"After:\\n\\t%v: %v, %v\\n\", p, *p, i)\n}\n\nfunc slice() {\n\tfmt.Printf(\"Slice:\\n\")\n\n\tvar a [10]byte\n\n\t\n\t\n\t\n\t\n\t\n\tvar h reflect.SliceHeader\n\th.Data = uintptr(unsafe.Pointer(&a)) \n\th.Len = len(a)\n\th.Cap = len(a)\n\n\t\n\ts := *(*[]byte)(unsafe.Pointer(&h))\n\n\tfmt.Printf(\"Before:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n\n\t\n\t\n\tcopy(s, \"A string.\")\n\n\tfmt.Printf(\"After:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n}\n\nfunc main() {\n\tpointer()\n\tfmt.Println()\n\n\tslice()\n}\n"}
{"id": 40107, "name": "Sequence of primorial primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n"}
{"id": 40108, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 40109, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 40110, "name": "Dining philosophers", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n"}
{"id": 40111, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 40112, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 40113, "name": "Logistic curve fitting in epidemiology", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n"}
{"id": 40114, "name": "Sorting algorithms_Strand sort", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n"}
{"id": 40115, "name": "Additive primes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n"}
{"id": 40116, "name": "Inverted syntax", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n"}
{"id": 40117, "name": "Inverted syntax", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n"}
{"id": 40118, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 40119, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 40120, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 40121, "name": "Delegates", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 40122, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 40123, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 40124, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 40125, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 40126, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 40127, "name": "Enforced immutability", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n"}
{"id": 40128, "name": "Sutherland-Hodgman polygon clipping", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n"}
{"id": 40129, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 40130, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 40131, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 40132, "name": "Spiral matrix", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n"}
{"id": 40133, "name": "Spiral matrix", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n"}
{"id": 40134, "name": "Optional parameters", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n"}
{"id": 40135, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 40136, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 40137, "name": "Call a foreign-language function", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 40138, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 40139, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 40140, "name": "Faulhaber's triangle", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n"}
{"id": 40141, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 40142, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 40143, "name": "Word wheel", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n"}
{"id": 40144, "name": "Array concatenation", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 40145, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 40146, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 40147, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 40148, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 40149, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 40150, "name": "Primes - allocate descendants to their ancestors", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n"}
{"id": 40151, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 40152, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 40153, "name": "First-class functions", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 40154, "name": "First-class functions", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 40155, "name": "Proper divisors", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 40156, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n"}
{"id": 40157, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n"}
{"id": 40158, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 40159, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 40160, "name": "Regular expressions", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 40161, "name": "Guess the number_With feedback (player)", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n"}
{"id": 40162, "name": "Hash from two arrays", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 40163, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 40164, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 40165, "name": "Fractal tree", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n"}
{"id": 40166, "name": "Colour pinstripe_Display", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n"}
{"id": 40167, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 40168, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 40169, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n"}
{"id": 40170, "name": "Animate a pendulum", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n"}
{"id": 40171, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 40172, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 40173, "name": "Create a file on magnetic tape", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n"}
{"id": 40174, "name": "Create a file on magnetic tape", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n"}
{"id": 40175, "name": "Sorting algorithms_Heapsort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 40176, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 40177, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 40178, "name": "Sierpinski carpet", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 40179, "name": "Sorting algorithms_Bogosort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 40180, "name": "Merge and aggregate datasets", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n"}
{"id": 40181, "name": "Euler method", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 40182, "name": "Sequence of non-squares", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 40183, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 40184, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 40185, "name": "JortSort", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n"}
{"id": 40186, "name": "Leap year", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 40187, "name": "Combinations and permutations", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n"}
{"id": 40188, "name": "Combinations and permutations", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n"}
{"id": 40189, "name": "Sort numbers lexicographically", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n"}
{"id": 40190, "name": "Number names", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 40191, "name": "Compare length of two strings", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 40192, "name": "Sorting algorithms_Shell sort", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 40193, "name": "Doubly-linked list_Definition", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n"}
{"id": 40194, "name": "Letter frequency", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 40195, "name": "Permutation test", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n"}
{"id": 40196, "name": "Möbius function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n"}
{"id": 40197, "name": "Increment a numerical string", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 40198, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 40199, "name": "Sorting algorithms_Permutation sort", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n"}
{"id": 40200, "name": "Averages_Arithmetic mean", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 40201, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 40202, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 40203, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 40204, "name": "Entropy", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n"}
{"id": 40205, "name": "Tokenize a string with escaping", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n"}
{"id": 40206, "name": "Hello world_Text", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n"}
{"id": 40207, "name": "Sexy primes", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n"}
{"id": 40208, "name": "Forward difference", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 40209, "name": "Primality by trial division", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 40210, "name": "Primality by trial division", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 40211, "name": "Evaluate binomial coefficients", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 40212, "name": "Collections", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 40213, "name": "Singly-linked list_Traversal", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 40214, "name": "Singly-linked list_Traversal", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 40215, "name": "Bitmap_Write a PPM file", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 40216, "name": "Delete a file", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 40217, "name": "Delete a file", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 40218, "name": "Discordian date", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n"}
{"id": 40219, "name": "Flipping bits game", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 40220, "name": "Flipping bits game", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 40221, "name": "Hickerson series of almost integers", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 40222, "name": "Hickerson series of almost integers", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 40223, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 40224, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 40225, "name": "String interpolation (included)", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 40226, "name": "String interpolation (included)", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 40227, "name": "Sorting algorithms_Patience sort", "C++": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <iterator>\n#include <algorithm>\n#include <cassert>\n\ntemplate <class E>\nstruct pile_less {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() < pile2.top();\n  }\n};\n\ntemplate <class E>\nstruct pile_greater {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() > pile2.top();\n  }\n};\n\n\ntemplate <class Iterator>\nvoid patience_sort(Iterator first, Iterator last) {\n  typedef typename std::iterator_traits<Iterator>::value_type E;\n  typedef std::stack<E> Pile;\n\n  std::vector<Pile> piles;\n  \n  for (Iterator it = first; it != last; it++) {\n    E& x = *it;\n    Pile newPile;\n    newPile.push(x);\n    typename std::vector<Pile>::iterator i =\n      std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());\n    if (i != piles.end())\n      i->push(x);\n    else\n      piles.push_back(newPile);\n  }\n\n  \n  \n  std::make_heap(piles.begin(), piles.end(), pile_greater<E>());\n  for (Iterator it = first; it != last; it++) {\n    std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());\n    Pile &smallPile = piles.back();\n    *it = smallPile.top();\n    smallPile.pop();\n    if (smallPile.empty())\n      piles.pop_back();\n    else\n      std::push_heap(piles.begin(), piles.end(), pile_greater<E>());\n  }\n  assert(piles.empty());\n}\n\nint main() {\n  int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n  patience_sort(a, a+sizeof(a)/sizeof(*a));\n  std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  return 0;\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n"}
{"id": 40228, "name": "Bioinformatics_Sequence mutation", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 40229, "name": "Bioinformatics_Sequence mutation", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 40230, "name": "Tau number", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"The first \" << limit << \" tau numbers are:\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            std::cout << std::setw(6) << n;\n            ++count;\n            if (count % 10 == 0)\n                std::cout << '\\n';\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n"}
{"id": 40231, "name": "Determinant and permanent", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 40232, "name": "Determinant and permanent", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 40233, "name": "Partition function P", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n"}
{"id": 40234, "name": "Partition function P", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n"}
{"id": 40235, "name": "Wireworld", "C++": "#include <ggi/ggi.h>\n#include <set>\n#include <map>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <unistd.h> \n\nenum cell_type { none, wire, head, tail };\n\n\n\n\n\n\n\nclass display\n{\npublic:\n  display(int sizex, int sizey, int pixsizex, int pixsizey,\n          ggi_color* colors);\n  ~display()\n  {\n    ggiClose(visual);\n    ggiExit();\n  }\n\n  void flush();\n  bool keypressed() { return ggiKbhit(visual); }\n  void clear();\n  void putpixel(int x, int y, cell_type c);\nprivate:\n  ggi_visual_t visual;\n  int size_x, size_y;\n  int pixel_size_x, pixel_size_y;\n  ggi_pixel pixels[4];\n};\n\ndisplay::display(int sizex, int sizey, int pixsizex, int pixsizey,\n                 ggi_color* colors):\n  pixel_size_x(pixsizex),\n  pixel_size_y(pixsizey)\n{\n  if (ggiInit() < 0)\n  {\n    std::cerr << \"couldn't open ggi\\n\";\n    exit(1);\n  }\n\n  visual = ggiOpen(NULL);\n  if (!visual)\n  {\n    ggiPanic(\"couldn't open visual\\n\");\n  }\n\n  ggi_mode mode;\n  if (ggiCheckGraphMode(visual, sizex, sizey,\n                        GGI_AUTO, GGI_AUTO, GT_4BIT,\n                        &mode) != 0)\n  {\n    if (GT_DEPTH(mode.graphtype) < 2) \n      ggiPanic(\"low-color displays are not supported!\\n\");\n  }\n  if (ggiSetMode(visual, &mode) != 0)\n  {\n    ggiPanic(\"couldn't set graph mode\\n\");\n  }\n  ggiAddFlags(visual, GGIFLAG_ASYNC);\n\n  size_x = mode.virt.x;\n  size_y = mode.virt.y;\n\n  for (int i = 0; i < 4; ++i)\n    pixels[i] = ggiMapColor(visual, colors+i);\n}\n\nvoid display::flush()\n{\n  \n  ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));\n\n  \n  ggiFlush(visual);\n\n  \n  \n  \n  ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));\n}\n\nvoid display::clear()\n{\n  ggiSetGCForeground(visual, pixels[0]);\n  ggiDrawBox(visual, 0, 0, size_x, size_y);\n}\n\nvoid display::putpixel(int x, int y, cell_type cell)\n{\n  \n  \n  ggiSetGCForeground(visual, pixels[cell]);\n  ggiDrawBox(visual,\n             x*pixel_size_x, y*pixel_size_y,\n             pixel_size_x, pixel_size_y);\n}\n\n\n\n\n\n\nclass wireworld\n{\npublic:\n  void set(int posx, int posy, cell_type type);\n  void draw(display& destination);\n  void step();\nprivate:\n  typedef std::pair<int, int> position;\n  typedef std::set<position> position_set;\n  typedef position_set::iterator positer;\n  position_set wires, heads, tails;\n};\n\nvoid wireworld::set(int posx, int posy, cell_type type)\n{\n  position p(posx, posy);\n  wires.erase(p);\n  heads.erase(p);\n  tails.erase(p);\n  switch(type)\n  {\n  case head:\n    heads.insert(p);\n    break;\n  case tail:\n    tails.insert(p);\n    break;\n  case wire:\n    wires.insert(p);\n    break;\n  }\n}\n\nvoid wireworld::draw(display& destination)\n{\n  destination.clear();\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    destination.putpixel(i->first, i->second, head);\n  for (positer i = tails.begin(); i != tails.end(); ++i)\n    destination.putpixel(i->first, i->second, tail);\n  for (positer i = wires.begin(); i != wires.end(); ++i)\n    destination.putpixel(i->first, i->second, wire);\n  destination.flush();\n}\n\nvoid wireworld::step()\n{\n  std::map<position, int> new_heads;\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    for (int dx = -1; dx <= 1; ++dx)\n      for (int dy = -1; dy <= 1; ++dy)\n      {\n        position pos(i->first + dx, i->second + dy);\n        if (wires.count(pos))\n          new_heads[pos]++;\n      }\n  wires.insert(tails.begin(), tails.end());\n  tails.swap(heads);\n  heads.clear();\n  for (std::map<position, int>::iterator i = new_heads.begin();\n       i != new_heads.end();\n       ++i)\n  {\n\n    if (i->second < 3)\n    {\n      wires.erase(i->first);\n      heads.insert(i->first);\n    }\n  }\n}\n\nggi_color colors[4] =\n  {{ 0x0000, 0x0000, 0x0000 },  \n   { 0x8000, 0x8000, 0x8000 },  \n   { 0xffff, 0xffff, 0x0000 },  \n   { 0xffff, 0x0000, 0x0000 }}; \n\nint main(int argc, char* argv[])\n{\n  int display_x = 800;\n  int display_y = 600;\n  int pixel_x = 5;\n  int pixel_y = 5;\n\n  if (argc < 2)\n  {\n    std::cerr << \"No file name given!\\n\";\n    return 1;\n  }\n\n  \n  std::ifstream f(argv[1]);\n  wireworld w;\n  std::string line;\n  int line_number = 0;\n  while (std::getline(f, line))\n  {\n    for (int col = 0; col < line.size(); ++col)\n    {\n      switch (line[col])\n      {\n      case 'h': case 'H':\n        w.set(col, line_number, head);\n        break;\n      case 't': case 'T':\n        w.set(col, line_number, tail);\n        break;\n      case 'w': case 'W': case '.':\n        w.set(col, line_number, wire);\n        break;\n      default:\n        std::cerr << \"unrecognized character: \" << line[col] << \"\\n\";\n        return 1;\n      case ' ':\n        ; \n      }\n    }\n    ++line_number;\n  }\n\n  display d(display_x, display_y, pixel_x, pixel_y, colors);\n\n  w.draw(d);\n\n  while (!d.keypressed())\n  {\n    usleep(100000);\n    w.step();\n    w.draw(d);\n  }\n  std::cout << std::endl;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n"}
{"id": 40236, "name": "Ray-casting algorithm", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nconst double epsilon = numeric_limits<float>().epsilon();\nconst numeric_limits<double> DOUBLE;\nconst double MIN = DOUBLE.min();\nconst double MAX = DOUBLE.max();\n\nstruct Point { const double x, y; };\n\nstruct Edge {\n    const Point a, b;\n\n    bool operator()(const Point& p) const\n    {\n        if (a.y > b.y) return Edge{ b, a }(p);\n        if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });\n        if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;\n        if (p.x < min(a.x, b.x)) return true;\n        auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;\n        auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;\n        return blue >= red;\n    }\n};\n\nstruct Figure {\n    const string  name;\n    const initializer_list<Edge> edges;\n\n    bool contains(const Point& p) const\n    {\n        auto c = 0;\n        for (auto e : edges) if (e(p)) c++;\n        return c % 2 != 0;\n    }\n\n    template<unsigned char W = 3>\n    void check(const initializer_list<Point>& points, ostream& os) const\n    {\n        os << \"Is point inside figure \" << name <<  '?' << endl;\n        for (auto p : points)\n            os << \"  (\" << setw(W) << p.x << ',' << setw(W) << p.y << \"): \" << boolalpha << contains(p) << endl;\n        os << endl;\n    }\n};\n\nint main()\n{\n    const initializer_list<Point> points =  { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };\n    const Figure square = { \"Square\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }\n    };\n\n    const Figure square_hole = { \"Square hole\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},\n           {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure strange = { \"Strange\",\n        {  {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},\n           {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure exagon = { \"Exagon\",\n        {  {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},\n           {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}\n        }\n    };\n\n    for(auto f : {square, square_hole, strange, exagon})\n        f.check(points, cout);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 40237, "name": "Elliptic curve arithmetic", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 40238, "name": "Elliptic curve arithmetic", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 40239, "name": "Count occurrences of a substring", "C++": "#include <iostream>\n#include <string>\n\n\nint countSubstring(const std::string& str, const std::string& sub)\n{\n    if (sub.length() == 0) return 0;\n    int count = 0;\n    for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n    {\n        ++count;\n    }\n    return count;\n}\n\nint main()\n{\n    std::cout << countSubstring(\"the three truths\", \"th\")    << '\\n';\n    std::cout << countSubstring(\"ababababab\", \"abab\")        << '\\n';\n    std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n    return 0;\n}\n", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n"}
{"id": 40240, "name": "Numbers with prime digits whose sum is 13", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 40241, "name": "Numbers with prime digits whose sum is 13", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 40242, "name": "Numbers with prime digits whose sum is 13", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 40243, "name": "String comparison", "C++": "#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <string>\n\ntemplate <typename T>\nvoid demo_compare(const T &a, const T &b, const std::string &semantically) {\n    std::cout << a << \" and \" << b << \" are \" << ((a == b) ? \"\" : \"not \")\n              << \"exactly \" << semantically << \" equal.\" << std::endl;\n\n    std::cout << a << \" and \" << b << \" are \" << ((a != b) ? \"\" : \"not \")\n              << semantically << \"inequal.\" << std::endl;\n\n    std::cout << a << \" is \" << ((a < b) ? \"\" : \"not \") << semantically\n              << \" ordered before \" << b << '.' << std::endl;\n\n    std::cout << a << \" is \" << ((a > b) ? \"\" : \"not \") << semantically\n              << \" ordered after \" << b << '.' << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n    \n    std::string a((argc > 1) ? argv[1] : \"1.2.Foo\");\n    std::string b((argc > 2) ? argv[2] : \"1.3.Bar\");\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    std::transform(a.begin(), a.end(), a.begin(), ::tolower);\n    std::transform(b.begin(), b.end(), b.begin(), ::tolower);\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    \n    double numA, numB;\n    std::istringstream(a) >> numA;\n    std::istringstream(b) >> numB;\n    demo_compare<double>(numA, numB, \"numerically\");\n    return (a == b);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n"}
{"id": 40244, "name": "Take notes on the command line", "C++": "#include <fstream>\n#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char **argv)\n{\n\tif(argc>1)\n\t{\n\t\tofstream Notes(note_file, ios::app);\n\t\ttime_t timer = time(NULL);\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\tNotes << asctime(localtime(&timer)) << '\\t';\n\t\t\tfor(int i=1;i<argc;i++)\n\t\t\t\tNotes << argv[i] << ' ';\n\t\t\tNotes << endl;\n\t\t\tNotes.close();\n\t\t}\n\t}\n\telse\n\t{\n\t\tifstream Notes(note_file, ios::in);\n\t\tstring line;\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\twhile(!Notes.eof())\n\t\t\t{\n\t\t\t\tgetline(Notes, line);\n\t\t\t\tcout << line << endl;\n\t\t\t}\n\t\t\tNotes.close();\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 40245, "name": "Take notes on the command line", "C++": "#include <fstream>\n#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char **argv)\n{\n\tif(argc>1)\n\t{\n\t\tofstream Notes(note_file, ios::app);\n\t\ttime_t timer = time(NULL);\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\tNotes << asctime(localtime(&timer)) << '\\t';\n\t\t\tfor(int i=1;i<argc;i++)\n\t\t\t\tNotes << argv[i] << ' ';\n\t\t\tNotes << endl;\n\t\t\tNotes.close();\n\t\t}\n\t}\n\telse\n\t{\n\t\tifstream Notes(note_file, ios::in);\n\t\tstring line;\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\twhile(!Notes.eof())\n\t\t\t{\n\t\t\t\tgetline(Notes, line);\n\t\t\t\tcout << line << endl;\n\t\t\t}\n\t\t\tNotes.close();\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 40246, "name": "Thiele's interpolation formula", "C++": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string.h>\n\nconstexpr unsigned int N = 32u;\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\nconstexpr unsigned int N2 = N * (N - 1u) / 2u;\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\ndouble ρ(double *x, double *y, double *r, int i, int n) {\n    if (n < 0)\n        return 0;\n    if (!n)\n        return y[i];\n\n    unsigned int idx = (N - 1 - n) * (N - n) / 2 + i;\n    if (r[idx] != r[idx])\n        r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2);\n    return r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, unsigned int n) {\n    return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\ninline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); }\ninline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); }\ninline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); }\n\nint main() {\n    constexpr double step = .05;\n    for (auto i = 0u; i < N; i++) {\n        xval[i] = i * step;\n        t_sin[i] = sin(xval[i]);\n        t_cos[i] = cos(xval[i]);\n        t_tan[i] = t_sin[i] / t_cos[i];\n    }\n    for (auto i = 0u; i < N2; i++)\n        r_sin[i] = r_cos[i] = r_tan[i] = NAN;\n\n    std::cout << std::setw(16) << std::setprecision(25)\n              << 6 * i_sin(.5) << std::endl\n              << 3 * i_cos(.5) << std::endl\n              << 4 * i_tan(1.) << std::endl;\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n"}
{"id": 40247, "name": "Fibonacci word", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 40248, "name": "Fibonacci word", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 40249, "name": "Fibonacci word", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 40250, "name": "Angles (geometric), normalization and conversion", "C++": "#include <functional>\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <sstream>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n\ntemplate<typename T>\nT normalize(T a, double b) { return std::fmod(a, b); }\n\ninline double d2d(double a) { return normalize<double>(a, 360); }\ninline double g2g(double a) { return normalize<double>(a, 400); }\ninline double m2m(double a) { return normalize<double>(a, 6400); }\ninline double r2r(double a) { return normalize<double>(a, 2*M_PI); }\n\ndouble d2g(double a) { return g2g(a * 10 / 9); }\ndouble d2m(double a) { return m2m(a * 160 / 9); }\ndouble d2r(double a) { return r2r(a * M_PI / 180); }\ndouble g2d(double a) { return d2d(a * 9 / 10); }\ndouble g2m(double a) { return m2m(a * 16); }\ndouble g2r(double a) { return r2r(a * M_PI / 200); }\ndouble m2d(double a) { return d2d(a * 9 / 160); }\ndouble m2g(double a) { return g2g(a / 16); }\ndouble m2r(double a) { return r2r(a * M_PI / 3200); }\ndouble r2d(double a) { return d2d(a * 180 / M_PI); }\ndouble r2g(double a) { return g2g(a * 200 / M_PI); }\ndouble r2m(double a) { return m2m(a * 3200 / M_PI); }\n\nvoid print(const std::vector<double> &values, const char *s, std::function<double(double)> f) {\n    using namespace std;\n    ostringstream out;\n    out << \"                  ┌───────────────────┐\\n\";\n    out << \"                  │ \" << setw(17) << s << \" │\\n\";\n    out << \"┌─────────────────┼───────────────────┤\\n\";\n    for (double i : values)\n        out << \"│ \" << setw(15) << fixed << i << defaultfloat << \" │ \" << setw(17) << fixed << f(i) << defaultfloat << \" │\\n\";\n    out << \"└─────────────────┴───────────────────┘\\n\";\n    auto str = out.str();\n    boost::algorithm::replace_all(str, \".000000\", \"       \");\n    cout << str;\n}\n\nint main() {\n    std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 };\n    print(values, \"normalized (deg)\", d2d);\n    print(values, \"normalized (grad)\", g2g);\n    print(values, \"normalized (mil)\", m2m);\n    print(values, \"normalized (rad)\", r2r);\n\n    print(values, \"deg -> grad \", d2g);\n    print(values, \"deg -> mil \", d2m);\n    print(values, \"deg -> rad \", d2r);\n\n    print(values, \"grad -> deg \", g2d);\n    print(values, \"grad -> mil \", g2m);\n    print(values, \"grad -> rad \", g2r);\n\n    print(values, \"mil -> deg \", m2d);\n    print(values, \"mil -> grad \", m2g);\n    print(values, \"mil -> rad \", m2r);\n\n    print(values, \"rad -> deg \", r2d);\n    print(values, \"rad -> grad \", r2g);\n    print(values, \"rad -> mil \", r2m);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n"}
{"id": 40251, "name": "Find common directory path", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::string longestPath( const std::vector<std::string> & , char ) ;\n\nint main( ) {\n   std::string dirs[ ] = {\n      \"/home/user1/tmp/coverage/test\" ,\n      \"/home/user1/tmp/covert/operator\" ,\n      \"/home/user1/tmp/coven/members\" } ;\n   std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;\n   std::cout << \"The longest common path of the given directories is \"\n             << longestPath( myDirs , '/' ) << \"!\\n\" ;\n   return 0 ;\n}\n\nstd::string longestPath( const std::vector<std::string> & dirs , char separator ) {\n   std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;\n   int maxCharactersCommon = vsi->length( ) ;\n   std::string compareString = *vsi ;\n   for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {\n      std::pair<std::string::const_iterator , std::string::const_iterator> p = \n\t std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;\n      if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) \n\t maxCharactersCommon = p.first - compareString.begin( ) ;\n   }\n   std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;\n   return compareString.substr( 0 , found ) ;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n"}
{"id": 40252, "name": "Verify distribution uniformity_Naive", "C++": "#include <map>\n#include <iostream>\n#include <cmath>\n\ntemplate<typename F>\n bool test_distribution(F f, int calls, double delta)\n{\n  typedef std::map<int, int> distmap;\n  distmap dist;\n\n  for (int i = 0; i < calls; ++i)\n    ++dist[f()];\n\n  double mean = 1.0/dist.size();\n\n  bool good = true;\n\n  for (distmap::iterator i = dist.begin(); i != dist.end(); ++i)\n  {\n    if (std::abs((1.0 * i->second)/calls - mean) > delta)\n    {\n      std::cout << \"Relative frequency \" << i->second/(1.0*calls)\n                << \" of result \" << i->first\n                << \" deviates by more than \" << delta\n                << \" from the expected value \" << mean << \"\\n\";\n      good = false;\n    }\n  }\n\n  return good;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 40253, "name": "Stirling numbers of the second kind", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 40254, "name": "Stirling numbers of the second kind", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 40255, "name": "Recaman's sequence", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 40256, "name": "Recaman's sequence", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 40257, "name": "Memory allocation", "C++": "#include <string>\n\nint main()\n{\n  int* p;\n\n  p = new int;    \n  delete p;       \n\n  p = new int(2); \n  delete p;       \n\n  std::string* p2;\n\n  p2 = new std::string; \n  delete p2;            \n\n  p = new int[10]; \n  delete[] p;      \n\n  p2 = new std::string[10]; \n  delete[] p2;              \n}\n", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n"}
{"id": 40258, "name": "Tic-tac-toe", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum players { Computer, Human, Draw, None };\nconst int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };\n\n\nclass ttt\n{\npublic:\n    ttt() { _p = rand() % 2; reset(); }\n\n    void play()\n    {\n\tint res = Draw;\n\twhile( true )\n\t{\n\t    drawGrid();\n\t    while( true )\n\t    {\n\t\tif( _p ) getHumanMove();\n\t\telse getComputerMove();\n\n\t\tdrawGrid();\n\n\t\tres = checkVictory();\n\t\tif( res != None ) break;\n\n\t\t++_p %= 2;\n\t    }\n\n\t    if( res == Human ) cout << \"CONGRATULATIONS HUMAN --- You won!\";\n\t    else if( res == Computer ) cout << \"NOT SO MUCH A SURPRISE --- I won!\";\n\t    else cout << \"It's a draw!\";\n\n\t    cout << endl << endl;\n\n\t    string r;\n\t    cout << \"Play again( Y / N )? \"; cin >> r;\n\t    if( r != \"Y\" && r != \"y\" ) return;\n\n\t    ++_p %= 2;\n\t    reset();\n\n\t}\n    }\n\nprivate:\n    void reset() \n    {\n\tfor( int x = 0; x < 9; x++ )\n\t    _field[x] = None;\n    }\n\n    void drawGrid()\n    {\n\tsystem( \"cls\" );\n\t\t\n        COORD c = { 0, 2 };\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\n\tcout << \" 1 | 2 | 3 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 4 | 5 | 6 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 7 | 8 | 9 \" << endl << endl << endl;\n\n\tint f = 0;\n\tfor( int y = 0; y < 5; y += 2 )\n\t    for( int x = 1; x < 11; x += 4 )\n\t    {\n\t\tif( _field[f] != None )\n\t\t{\n\t\t    COORD c = { x, 2 + y };\n\t\t    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\t\t    string o = _field[f] == Computer ? \"X\" : \"O\";\n\t\t    cout << o;\n\t\t}\n\t\tf++;\n\t    }\n\n        c.Y = 9;\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n    }\n\n    int checkVictory()\n    {\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    if( _field[iWin[i][0]] != None &&\n\t\t_field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )\n\t    {\n\t\treturn _field[iWin[i][0]];\n\t    }\n\t}\n\n\tint i = 0;\n\tfor( int f = 0; f < 9; f++ )\n\t{\n\t    if( _field[f] != None )\n\t\ti++;\n\t}\n\tif( i == 9 ) return Draw;\n\n\treturn None;\n    }\n\n    void getHumanMove()\n    {\n\tint m;\n\tcout << \"Enter your move ( 1 - 9 ) \";\n\twhile( true )\n\t{\n\t    m = 0;\n\t    do\n\t    { cin >> m; }\n\t    while( m < 1 && m > 9 );\n\n\t    if( _field[m - 1] != None )\n\t\tcout << \"Invalid move. Try again!\" << endl;\n\t    else break;\n\t}\n\n\t_field[m - 1] = Human;\n    }\n\n    void getComputerMove()\n    {\n\tint move = 0;\n\n\tdo{ move = rand() % 9; }\n\twhile( _field[move] != None );\n\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];\n\n\t    if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )\n\t    {\n\t\tmove = try3;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) \n\t    {\t\t\t\n\t\tmove = try2;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )\n\t    {\n\t\tmove = try1;\n\t\tif( _field[try2] == Computer ) break;\n\t    }\n        }\n\t_field[move] = Computer;\n\t\t\n    }\n\n\nint _p;\nint _field[9];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n\n    ttt tic;\n    tic.play();\n\n    return 0;\n}\n\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n"}
{"id": 40259, "name": "Integer sequence", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 40260, "name": "Integer sequence", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 40261, "name": "Entropy_Narcissist", "C++": "#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\n\nstring readFile (string path) {\n    string contents;\n    string line;\n    ifstream inFile(path);\n    while (getline (inFile, line)) {\n        contents.append(line);\n        contents.append(\"\\n\");\n    }\n    inFile.close();\n    return contents;\n}\n\ndouble entropy (string X) {\n    const int MAXCHAR = 127;\n    int N = X.length();\n    int count[MAXCHAR];\n    double count_i;\n    char ch;\n    double sum = 0.0;\n    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;\n    for (int pos = 0; pos < N; pos++) {\n        ch = X[pos];\n        count[(int)ch]++;\n    }\n    for (int n_i = 0; n_i < MAXCHAR; n_i++) {\n        count_i = count[n_i];\n        if (count_i > 0) sum -= count_i / N * log2(count_i / N);\n    }\n    return sum;\n}\n\nint main () {\n    cout<<entropy(readFile(\"entropy.cpp\"));\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n"}
{"id": 40262, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 40263, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 40264, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 40265, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 40266, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 40267, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 40268, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 40269, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 40270, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 40271, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 40272, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 40273, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 40274, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 40275, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 40276, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 40277, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 40278, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n"}
{"id": 40279, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n"}
{"id": 40280, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 40281, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 40282, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 40283, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 40284, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 40285, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 40286, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n"}
{"id": 40287, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n"}
{"id": 40288, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 40289, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 40290, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n"}
{"id": 40291, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n"}
{"id": 40292, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 40293, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 40294, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 40295, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 40296, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 40297, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 40298, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n"}
{"id": 40299, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n"}
{"id": 40300, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n"}
{"id": 40301, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n"}
{"id": 40302, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 40303, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 40304, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 40305, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 40306, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 40307, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 40308, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 40309, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 40310, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 40311, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 40312, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 40313, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 40314, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 40315, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 40316, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 40317, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 40318, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 40319, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 40320, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 40321, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 40322, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 40323, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 40324, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 40325, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 40326, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n"}
{"id": 40327, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n"}
{"id": 40328, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 40329, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 40330, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 40331, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 40332, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 40333, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 40334, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 40335, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 40336, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 40337, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 40338, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 40339, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 40340, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 40341, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 40342, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 40343, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 40344, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 40345, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 40346, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 40347, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 40348, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 40349, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 40350, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 40351, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 40352, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 40353, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 40354, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 40355, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 40356, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 40357, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 40358, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n"}
{"id": 40359, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n"}
{"id": 40360, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 40361, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 40362, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n"}
{"id": 40363, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n"}
{"id": 40364, "name": "Hello world_Text", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n"}
{"id": 40365, "name": "Hello world_Text", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n"}
{"id": 40366, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 40367, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 40368, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 40369, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 40370, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 40371, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 40372, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 40373, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 40374, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 40375, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 40376, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 40377, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 40378, "name": "Discordian date", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n"}
{"id": 40379, "name": "Discordian date", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n"}
{"id": 40380, "name": "String interpolation (included)", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 40381, "name": "String interpolation (included)", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 40382, "name": "Sorting algorithms_Patience sort", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n"}
{"id": 40383, "name": "Sorting algorithms_Patience sort", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n"}
{"id": 40384, "name": "Wireworld", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n"}
{"id": 40385, "name": "Wireworld", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n"}
{"id": 40386, "name": "Ray-casting algorithm", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 40387, "name": "Ray-casting algorithm", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 40388, "name": "Count occurrences of a substring", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n"}
{"id": 40389, "name": "Count occurrences of a substring", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n"}
{"id": 40390, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n"}
{"id": 40391, "name": "Dragon curve", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n"}
{"id": 40392, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n"}
{"id": 40393, "name": "Doubly-linked list_Element insertion", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n"}
{"id": 40394, "name": "Quickselect algorithm", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n"}
{"id": 40395, "name": "Non-decimal radices_Convert", "Python": "i = int('1a',16)  \n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 40396, "name": "Non-decimal radices_Convert", "Python": "i = int('1a',16)  \n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 40397, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n"}
{"id": 40398, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 40399, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 40400, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 40401, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 40402, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 40403, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 40404, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 40405, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 40406, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n"}
{"id": 40407, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 40408, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 40409, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 40410, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 40411, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 40412, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 40413, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n"}
{"id": 40414, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 40415, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 40416, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n"}
{"id": 40417, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n"}
{"id": 40418, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 40419, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 40420, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 40421, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 40422, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 40423, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 40424, "name": "Dining philosophers", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n"}
{"id": 40425, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 40426, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 40427, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40428, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40429, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 40430, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 40431, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 40432, "name": "Spiral matrix", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n"}
{"id": 40433, "name": "Optional parameters", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n"}
{"id": 40434, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n"}
{"id": 40435, "name": "Faulhaber's triangle", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40436, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 40437, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 40438, "name": "Word wheel", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n"}
{"id": 40439, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 40440, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 40441, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 40442, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 40443, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 40444, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 40445, "name": "Primes - allocate descendants to their ancestors", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n"}
{"id": 40446, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40447, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40448, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n"}
{"id": 40449, "name": "XML_Output", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n"}
{"id": 40450, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 40451, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 40452, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 40453, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n"}
{"id": 40454, "name": "Colour pinstripe_Display", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n"}
{"id": 40455, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n"}
{"id": 40456, "name": "Animate a pendulum", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n"}
{"id": 40457, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 40458, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 40459, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 40460, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 40461, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "VB": "Option Base {0|1}\n"}
{"id": 40462, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "VB": "Option Base {0|1}\n"}
{"id": 40463, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 40464, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n"}
{"id": 40465, "name": "Euler method", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n"}
{"id": 40466, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 40467, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 40468, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 40469, "name": "JortSort", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n"}
{"id": 40470, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n"}
{"id": 40471, "name": "Combinations and permutations", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n"}
{"id": 40472, "name": "Sort numbers lexicographically", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n"}
{"id": 40473, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n"}
{"id": 40474, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n"}
{"id": 40475, "name": "Doubly-linked list_Definition", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n"}
{"id": 40476, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n"}
{"id": 40477, "name": "Increment a numerical string", "Python": "next = str(int('123') + 1)\n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 40478, "name": "Increment a numerical string", "Python": "next = str(int('123') + 1)\n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 40479, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 40480, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n"}
{"id": 40481, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40482, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40483, "name": "Tokenize a string with escaping", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n"}
{"id": 40484, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n"}
{"id": 40485, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n"}
{"id": 40486, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 40487, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 40488, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 40489, "name": "Singly-linked list_Traversal", "Python": "for node in lst:\n    print node.value\n", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n"}
{"id": 40490, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n"}
{"id": 40491, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n"}
{"id": 40492, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 40493, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 40494, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n"}
{"id": 40495, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n"}
{"id": 40496, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n"}
{"id": 40497, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "VB": "Imports System.Math\n\nModule RayCasting\n\n    Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}\n    Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}\n    Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}\n    Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}\n    Private shapes As Integer()()() = {square, squareHole, strange, hexagon}\n\n    Public Sub Main()\n        Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}\n\n        For Each shape As Integer()() In shapes\n            For Each point As Double() In testPoints\n                Console.Write(String.Format(\"{0} \", Contains(shape, point).ToString.PadLeft(7)))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\n    Private Function Contains(shape As Integer()(), point As Double()) As Boolean\n\n        Dim inside As Boolean = False\n        Dim length As Integer = shape.Length\n\n        For i As Integer = 0 To length - 1\n            If Intersects(shape(i), shape((i + 1) Mod length), point) Then\n                inside = Not inside\n            End If\n        Next\n\n        Return inside\n    End Function\n\n    Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean\n\n        If a(1) > b(1) Then Return Intersects(b, a, p)\n        If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001\n        If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False\n        If p(0) < Min(a(0), b(0)) Then Return True\n        Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))\n        Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))\n\n        Return red >= blue\n    End Function\nEnd Module\n"}
{"id": 40498, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "VB": "Function CountSubstring(str,substr)\n\tCountSubstring = 0\n\tFor i = 1 To Len(str)\n\t\tIf Len(str) >= Len(substr) Then\n\t\t\tIf InStr(i,str,substr) Then\n\t\t\t\tCountSubstring = CountSubstring + 1\n\t\t\t\ti = InStr(i,str,substr) + Len(substr) - 1\n\t\t\tEnd If\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write CountSubstring(\"the three truths\",\"th\") & vbCrLf\nWScript.StdOut.Write CountSubstring(\"ababababab\",\"abab\") & vbCrLf\n"}
{"id": 40499, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40500, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40501, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40502, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "VB": "Imports System.IO\n\nModule Notes\n    Function Main(ByVal cmdArgs() As String) As Integer\n        Try\n            If cmdArgs.Length = 0 Then\n                Using sr As New StreamReader(\"NOTES.TXT\")\n                    Console.WriteLine(sr.ReadToEnd)\n                End Using\n            Else\n                Using sw As New StreamWriter(\"NOTES.TXT\", True)\n                    sw.WriteLine(Date.Now.ToString())\n                    sw.WriteLine(\"{0}{1}\", ControlChars.Tab, String.Join(\" \", cmdArgs))\n                End Using\n            End If\n        Catch\n        End Try\n    End Function\nEnd Module\n"}
{"id": 40503, "name": "Find common directory path", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n", "VB": "Public Function CommonDirectoryPath(ParamArray Paths()) As String\nDim v As Variant\nDim Path() As String, s As String\nDim i As Long, j As Long, k As Long\nConst PATH_SEPARATOR As String = \"/\"\n  \n  For Each v In Paths\n    ReDim Preserve Path(0 To i)\n    Path(i) = v\n    i = i + 1\n  Next v\n  \n  k = 1\n  \n  Do\n    For i = 0 To UBound(Path)\n      If i Then\n        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then\n          Exit Do\n        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then\n          Exit Do\n        End If\n      Else\n        j = InStr(k, Path(i), PATH_SEPARATOR)\n        If j = 0 Then\n          Exit Do\n        End If\n      End If\n    Next i\n    s = Left$(Path(0), j + CLng(k <> 1))\n    k = j + 1\n  Loop\n  CommonDirectoryPath = s\n  \nEnd Function\n\nSub Main()\n\n\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/home/user1/tmp\"\n \n Debug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\", _\n \"/home/user1/abc/coven/members\") = _\n \"/home/user1\"\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/hope/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/\"\n\nEnd Sub\n"}
{"id": 40504, "name": "Bitwise operations", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n"}
{"id": 40505, "name": "Dragon curve", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n"}
{"id": 40506, "name": "Read a file line by line", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n"}
{"id": 40507, "name": "Doubly-linked list_Element insertion", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n"}
{"id": 40508, "name": "Quickselect algorithm", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n"}
{"id": 40509, "name": "Non-decimal radices_Convert", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 40510, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n"}
{"id": 40511, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 40512, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 40513, "name": "Classes", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 40514, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 40515, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 40516, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 40517, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 40518, "name": "Anonymous recursion", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n"}
{"id": 40519, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 40520, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 40521, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 40522, "name": "Create a file", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 40523, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 40524, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 40525, "name": "Spiral matrix", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n"}
{"id": 40526, "name": "Faulhaber's triangle", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40527, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 40528, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 40529, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 40530, "name": "User input_Text", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 40531, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 40532, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40533, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40534, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n"}
{"id": 40535, "name": "XML_Output", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n"}
{"id": 40536, "name": "Regular expressions", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 40537, "name": "Hash from two arrays", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n"}
{"id": 40538, "name": "Animate a pendulum", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n"}
{"id": 40539, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 40540, "name": "Sierpinski carpet", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 40541, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n"}
{"id": 40542, "name": "Euler method", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n"}
{"id": 40543, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 40544, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 40545, "name": "JortSort", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n"}
{"id": 40546, "name": "Leap year", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n"}
{"id": 40547, "name": "Sort numbers lexicographically", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n"}
{"id": 40548, "name": "Number names", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n"}
{"id": 40549, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n"}
{"id": 40550, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 40551, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 40552, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 40553, "name": "Averages_Arithmetic mean", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n"}
{"id": 40554, "name": "Tokenize a string with escaping", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n"}
{"id": 40555, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n"}
{"id": 40556, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n"}
{"id": 40557, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n"}
{"id": 40558, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 40559, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 40560, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 40561, "name": "Singly-linked list_Traversal", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n"}
{"id": 40562, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n"}
{"id": 40563, "name": "Delete a file", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n"}
{"id": 40564, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 40565, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 40566, "name": "String interpolation (included)", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n"}
{"id": 40567, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40568, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40569, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n"}
{"id": 40570, "name": "Take notes on the command line", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n", "VB": "Imports System.IO\n\nModule Notes\n    Function Main(ByVal cmdArgs() As String) As Integer\n        Try\n            If cmdArgs.Length = 0 Then\n                Using sr As New StreamReader(\"NOTES.TXT\")\n                    Console.WriteLine(sr.ReadToEnd)\n                End Using\n            Else\n                Using sw As New StreamWriter(\"NOTES.TXT\", True)\n                    sw.WriteLine(Date.Now.ToString())\n                    sw.WriteLine(\"{0}{1}\", ControlChars.Tab, String.Join(\" \", cmdArgs))\n                End Using\n            End If\n        Catch\n        End Try\n    End Function\nEnd Module\n"}
{"id": 40571, "name": "Find common directory path", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n", "VB": "Public Function CommonDirectoryPath(ParamArray Paths()) As String\nDim v As Variant\nDim Path() As String, s As String\nDim i As Long, j As Long, k As Long\nConst PATH_SEPARATOR As String = \"/\"\n  \n  For Each v In Paths\n    ReDim Preserve Path(0 To i)\n    Path(i) = v\n    i = i + 1\n  Next v\n  \n  k = 1\n  \n  Do\n    For i = 0 To UBound(Path)\n      If i Then\n        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then\n          Exit Do\n        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then\n          Exit Do\n        End If\n      Else\n        j = InStr(k, Path(i), PATH_SEPARATOR)\n        If j = 0 Then\n          Exit Do\n        End If\n      End If\n    Next i\n    s = Left$(Path(0), j + CLng(k <> 1))\n    k = j + 1\n  Loop\n  CommonDirectoryPath = s\n  \nEnd Function\n\nSub Main()\n\n\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/home/user1/tmp\"\n \n Debug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\", _\n \"/home/user1/abc/coven/members\") = _\n \"/home/user1\"\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/hope/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/\"\n\nEnd Sub\n"}
{"id": 40572, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n"}
{"id": 40573, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n"}
{"id": 40574, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 40575, "name": "Dragon curve", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n"}
{"id": 40576, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 40577, "name": "Doubly-linked list_Element insertion", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n"}
{"id": 40578, "name": "Smarandache prime-digital sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n"}
{"id": 40579, "name": "Quickselect algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n"}
{"id": 40580, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "Python": "i = int('1a',16)  \n"}
{"id": 40581, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 40582, "name": "Main step of GOST 28147-89", "Go": "package main\n\nimport \"fmt\"\n\ntype sBox [8][16]byte\n\ntype gost struct {\n    k87, k65, k43, k21 [256]byte\n    enc                []byte\n}\n\nfunc newGost(s *sBox) *gost {\n    var g gost\n    for i := range g.k87 {\n        g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]\n        g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]\n        g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]\n        g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]\n    }\n    g.enc = make([]byte, 8)\n    return &g\n}\n\nfunc (g *gost) f(x uint32) uint32 {\n    x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |\n        uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])\n    return x<<11 | x>>(32-11)\n}\n\n\n\n\n\n\nvar cbrf = sBox{\n    {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},\n    {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},\n    {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},\n    {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},\n    {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},\n    {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},\n    {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},\n    {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},\n}\n\nfunc u32(b []byte) uint32 {\n    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc b4(u uint32, b []byte) {\n    b[0] = byte(u)\n    b[1] = byte(u >> 8)\n    b[2] = byte(u >> 16)\n    b[3] = byte(u >> 24)\n}\n\nfunc (g *gost) mainStep(input []byte, key []byte) {\n    key32 := u32(key)\n    input1 := u32(input[:4])\n    input2 := u32(input[4:])\n    b4(g.f(key32+input1)^input2, g.enc[:4])\n    copy(g.enc[4:], input[:4])\n}\n\nfunc main() {\n    input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}\n    key := []byte{0xF9, 0x04, 0xC1, 0xE2}\n\n    g := newGost(&cbrf)\n    g.mainStep(input, key)\n    for _, b := range g.enc {\n        fmt.Printf(\"[%02x]\", b)\n    }\n    fmt.Println()\n}\n", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n"}
{"id": 40583, "name": "State name puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n"}
{"id": 40584, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 40585, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 40586, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 40587, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 40588, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 40589, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 40590, "name": "LZW compression", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 40591, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 40592, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 40593, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 40594, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 40595, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40596, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40597, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40598, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 40599, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n"}
{"id": 40600, "name": "Mertens function", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n"}
{"id": 40601, "name": "Mertens function", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n"}
{"id": 40602, "name": "Order by pair comparisons", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n"}
{"id": 40603, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 40604, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 40605, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 40606, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n"}
{"id": 40607, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 40608, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 40609, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 40610, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 40611, "name": "Legendre prime counting function", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n"}
{"id": 40612, "name": "Use another language to call a function", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n"}
{"id": 40613, "name": "Longest string challenge", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 40614, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 40615, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 40616, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 40617, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 40618, "name": "Unprimeable numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n"}
{"id": 40619, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 40620, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n"}
{"id": 40621, "name": "Chernick's Carmichael numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n"}
{"id": 40622, "name": "Chernick's Carmichael numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n"}
{"id": 40623, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 40624, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n"}
{"id": 40625, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 40626, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n"}
{"id": 40627, "name": "Sequence of primorial primes", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n"}
{"id": 40628, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 40629, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 40630, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 40631, "name": "Dining philosophers", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n"}
{"id": 40632, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 40633, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 40634, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 40635, "name": "Logistic curve fitting in epidemiology", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n"}
{"id": 40636, "name": "Sorting algorithms_Strand sort", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n"}
{"id": 40637, "name": "Additive primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n"}
{"id": 40638, "name": "Inverted syntax", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n", "Python": "x = truevalue if condition else falsevalue\n"}
{"id": 40639, "name": "Inverted syntax", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n", "Python": "x = truevalue if condition else falsevalue\n"}
{"id": 40640, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 40641, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n"}
{"id": 40642, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 40643, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 40644, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n"}
{"id": 40645, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 40646, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 40647, "name": "Enforced immutability", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 40648, "name": "Sutherland-Hodgman polygon clipping", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n"}
{"id": 40649, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 40650, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 40651, "name": "Spiral matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n"}
{"id": 40652, "name": "Optional parameters", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n"}
{"id": 40653, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 40654, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n"}
{"id": 40655, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 40656, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 40657, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 40658, "name": "Faulhaber's triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40659, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 40660, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 40661, "name": "Word wheel", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n"}
{"id": 40662, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 40663, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 40664, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 40665, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 40666, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 40667, "name": "Primes - allocate descendants to their ancestors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n"}
{"id": 40668, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 40669, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 40670, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 40671, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 40672, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 40673, "name": "XML_Output", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n"}
{"id": 40674, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 40675, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 40676, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 40677, "name": "Guess the number_With feedback (player)", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n"}
{"id": 40678, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 40679, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 40680, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 40681, "name": "Fractal tree", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n"}
{"id": 40682, "name": "Colour pinstripe_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n"}
{"id": 40683, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 40684, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n"}
{"id": 40685, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n"}
{"id": 40686, "name": "Animate a pendulum", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n"}
{"id": 40687, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 40688, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 40689, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 40690, "name": "Create a file on magnetic tape", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n"}
{"id": 40691, "name": "Create a file on magnetic tape", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n"}
{"id": 40692, "name": "Sorting algorithms_Heapsort", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n"}
{"id": 40693, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 40694, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 40695, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 40696, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 40697, "name": "Merge and aggregate datasets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n"}
{"id": 40698, "name": "Euler method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n"}
{"id": 40699, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 40700, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 40701, "name": "JortSort", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n"}
{"id": 40702, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 40703, "name": "Combinations and permutations", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n"}
{"id": 40704, "name": "Sort numbers lexicographically", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n"}
{"id": 40705, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 40706, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 40707, "name": "Sorting algorithms_Shell sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 40708, "name": "Doubly-linked list_Definition", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n"}
{"id": 40709, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 40710, "name": "Permutation test", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n"}
{"id": 40711, "name": "Möbius function", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n"}
{"id": 40712, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "Python": "next = str(int('123') + 1)\n"}
{"id": 40713, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 40714, "name": "Sorting algorithms_Permutation sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n"}
{"id": 40715, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 40716, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 40717, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 40718, "name": "Entropy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 40719, "name": "Tokenize a string with escaping", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n"}
{"id": 40720, "name": "Sexy primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n"}
{"id": 40721, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 40722, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 40723, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 40724, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 40725, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 40726, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "Python": "for node in lst:\n    print node.value\n"}
{"id": 40727, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 40728, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 40729, "name": "Discordian date", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 40730, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 40731, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n"}
{"id": 40732, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 40733, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n"}
{"id": 40734, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 40735, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 40736, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 40737, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 40738, "name": "Sorting algorithms_Patience sort", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n"}
{"id": 40739, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 40740, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n"}
{"id": 40741, "name": "Tau number", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n"}
{"id": 40742, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 40743, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 40744, "name": "Partition function P", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n"}
{"id": 40745, "name": "Wireworld", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n"}
{"id": 40746, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 40747, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 40748, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 40749, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 40750, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n"}
{"id": 40751, "name": "Count occurrences of a substring", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 40752, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 40753, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 40754, "name": "String comparison", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n"}
{"id": 40755, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 40756, "name": "Thiele's interpolation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n"}
{"id": 40757, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 40758, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n"}
{"id": 40759, "name": "Angles (geometric), normalization and conversion", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n"}
{"id": 40760, "name": "Find common directory path", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n"}
{"id": 40761, "name": "Verify distribution uniformity_Naive", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n"}
{"id": 40762, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 40763, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n"}
{"id": 40764, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 40765, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 40766, "name": "Memory allocation", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n"}
{"id": 40767, "name": "Tic-tac-toe", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n"}
{"id": 40768, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 40769, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 40770, "name": "Entropy_Narcissist", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n"}
{"id": 40771, "name": "Entropy_Narcissist", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n"}
{"id": 40772, "name": "DNS query", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n"}
{"id": 40773, "name": "DNS query", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n"}
{"id": 40774, "name": "Peano curve", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar points []gg.Point\n\nconst width = 81\n\nfunc peano(x, y, lg, i1, i2 int) {\n    if lg == 1 {\n        px := float64(width-x) * 10\n        py := float64(width-y) * 10\n        points = append(points, gg.Point{px, py})\n        return\n    }\n    lg /= 3\n    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)\n    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)\n    peano(x+lg, y+lg, lg, i1, 1-i2)\n    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)\n    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)\n    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)\n    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)\n    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)\n    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)\n}\n\nfunc main() {\n    peano(0, 0, width, 0, 0)\n    dc := gg.NewContext(820, 820)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for _, p := range points {\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetRGB(1, 0, 1) \n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"peano.png\")\n}\n", "Python": "import turtle as tt\nimport inspect\n\nstack = [] \ndef peano(iterations=1):\n    global stack\n\n    \n    ivan = tt.Turtle(shape = \"classic\", visible = True)\n\n\n    \n    screen = tt.Screen()\n    screen.title(\"Desenhin do Peano\")\n    screen.bgcolor(\"\n    screen.delay(0) \n    screen.setup(width=0.95, height=0.9)\n\n    \n    walk = 1\n\n    def screenlength(k):\n        \n        \n        if k != 0:\n            length = screenlength(k-1)\n            return 2*length + 1\n        else: return 0\n\n    kkkj = screenlength(iterations)\n    screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)\n    ivan.color(\"\n\n\n    \n    def step1(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n    def step2(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n\n    \n    ivan.left(90)\n    step2(iterations)\n\n    tt.done()\n\nif __name__ == \"__main__\":\n    peano(4)\n    import pylab as P \n    P.plot(stack)\n    P.show()\n"}
{"id": 40775, "name": "Seven-sided dice from five-sided dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n"}
{"id": 40776, "name": "Seven-sided dice from five-sided dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n"}
{"id": 40777, "name": "Solve the no connection puzzle", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n"}
{"id": 40778, "name": "Solve the no connection puzzle", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n"}
{"id": 40779, "name": "Extensible prime generator", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"fmt\"\n)\n\nfunc main() {\n    p := newP()\n    fmt.Print(\"First twenty: \")\n    for i := 0; i < 20; i++ {\n        fmt.Print(p(), \" \")\n    }\n    fmt.Print(\"\\nBetween 100 and 150: \")\n    n := p()\n    for n <= 100 {\n        n = p()\n    }\n    for ; n < 150; n = p() {\n        fmt.Print(n, \" \")\n    }\n    for n <= 7700 {\n        n = p()\n    }\n    c := 0\n    for ; n < 8000; n = p() {\n        c++\n    }\n    fmt.Println(\"\\nNumber beween 7,700 and 8,000:\", c)\n    p = newP()\n    for i := 1; i < 10000; i++ {\n        p()\n    }\n    fmt.Println(\"10,000th prime:\", p())\n}\n\nfunc newP() func() int {\n    n := 1\n    var pq pQueue\n    top := &pMult{2, 4, 0}\n    return func() int {\n        for {\n            n++\n            if n < top.pMult { \n                heap.Push(&pq, &pMult{prime: n, pMult: n * n})\n                top = pq[0]\n                return n\n            }\n            \n            for top.pMult == n {\n                top.pMult += top.prime\n                heap.Fix(&pq, 0)\n                top = pq[0]\n            }\n        }\n    }\n}\n\ntype pMult struct {\n    prime int\n    pMult int\n    index int\n}\n\ntype pQueue []*pMult\n\nfunc (q pQueue) Len() int           { return len(q) }\nfunc (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }\nfunc (q pQueue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n    q[i].index = i\n    q[j].index = j\n}\nfunc (p *pQueue) Push(x interface{}) {\n    q := *p\n    e := x.(*pMult)\n    e.index = len(q)\n    *p = append(q, e)\n}\nfunc (p *pQueue) Pop() interface{} {\n    q := *p\n    last := len(q) - 1\n    e := q[last]\n    *p = q[:last]\n    return e\n}\n", "Python": "islice(count(7), 0, None, 2)\n"}
{"id": 40780, "name": "Rock-paper-scissors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n", "Python": "from random import choice\n\nrules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}\nprevious = ['rock', 'paper', 'scissors']\n\nwhile True:\n    human = input('\\nchoose your weapon: ')\n    computer = rules[choice(previous)]  \n\n    if human in ('quit', 'exit'): break\n\n    elif human in rules:\n        previous.append(human)\n        print('the computer played', computer, end='; ')\n\n        if rules[computer] == human:  \n            print('yay you win!')\n        elif rules[human] == computer:  \n            print('the computer beat you... :(')\n        else: print(\"it's a tie!\")\n\n    else: print(\"that's not a valid choice\")\n"}
{"id": 40781, "name": "Create a two-dimensional array at runtime", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n"}
{"id": 40782, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n"}
{"id": 40783, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n"}
{"id": 40784, "name": "Vigenère cipher_Cryptanalysis", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar encoded = \n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [26]float64{\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n}\n\nfunc sum(a []float64) (sum float64) {\n    for _, f := range a {\n        sum += f\n    }\n    return\n}\n\nfunc bestMatch(a []float64) int {\n    sum := sum(a)\n    bestFit, bestRotate := 1e100, 0\n    for rotate := 0; rotate < 26; rotate++ {\n        fit := 0.0\n        for i := 0; i < 26; i++ {\n            d := a[(i+rotate)%26]/sum - freq[i]\n            fit += d * d / freq[i]\n        }\n        if fit < bestFit {\n            bestFit, bestRotate = fit, rotate\n        }\n    }\n    return bestRotate\n}\n\nfunc freqEveryNth(msg []int, key []byte) float64 {\n    l := len(msg)\n    interval := len(key)\n    out := make([]float64, 26)\n    accu := make([]float64, 26)\n    for j := 0; j < interval; j++ {\n        for k := 0; k < 26; k++ {\n            out[k] = 0.0\n        }\n        for i := j; i < l; i += interval {\n            out[msg[i]]++\n        }\n        rot := bestMatch(out)\n        key[j] = byte(rot + 65)\n        for i := 0; i < 26; i++ {\n            accu[i] += out[(i+rot)%26]\n        }\n    }\n    sum := sum(accu)\n    ret := 0.0\n    for i := 0; i < 26; i++ {\n        d := accu[i]/sum - freq[i]\n        ret += d * d / freq[i]\n    }\n    return ret\n}\n\nfunc decrypt(text, key string) string {\n    var sb strings.Builder\n    ki := 0\n    for _, c := range text {\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        ci := (c - rune(key[ki]) + 26) % 26\n        sb.WriteRune(ci + 65)\n        ki = (ki + 1) % len(key)\n    }\n    return sb.String()\n}\n\nfunc main() {\n    enc := strings.Replace(encoded, \" \", \"\", -1)\n    txt := make([]int, len(enc))\n    for i := 0; i < len(txt); i++ {\n        txt[i] = int(enc[i] - 'A')\n    }\n    bestFit, bestKey := 1e100, \"\"\n    fmt.Println(\"  Fit     Length   Key\")\n    for j := 1; j <= 26; j++ {\n        key := make([]byte, j)\n        fit := freqEveryNth(txt, key)\n        sKey := string(key)\n        fmt.Printf(\"%f    %2d     %s\", fit, j, sKey)\n        if fit < bestFit {\n            bestFit, bestKey = fit, sKey\n            fmt.Print(\" <--- best so far\")\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nBest key :\", bestKey)\n    fmt.Printf(\"\\nDecrypted text:\\n%s\\n\", decrypt(enc, bestKey))\n}\n", "Python": "from string import uppercase\nfrom operator import itemgetter\n\ndef vigenere_decrypt(target_freqs, input):\n    nchars = len(uppercase)\n    ordA = ord('A')\n    sorted_targets = sorted(target_freqs)\n\n    def frequency(input):\n        result = [[c, 0.0] for c in uppercase]\n        for c in input:\n            result[c - ordA][1] += 1\n        return result\n\n    def correlation(input):\n        result = 0.0\n        freq = frequency(input)\n        freq.sort(key=itemgetter(1))\n\n        for i, f in enumerate(freq):\n            result += f[1] * sorted_targets[i]\n        return result\n\n    cleaned = [ord(c) for c in input.upper() if c.isupper()]\n    best_len = 0\n    best_corr = -100.0\n\n    \n    \n    for i in xrange(2, len(cleaned) // 20):\n        pieces = [[] for _ in xrange(i)]\n        for j, c in enumerate(cleaned):\n            pieces[j % i].append(c)\n\n        \n        \n        corr = -0.5 * i + sum(correlation(p) for p in pieces)\n\n        if corr > best_corr:\n            best_len = i\n            best_corr = corr\n\n    if best_len == 0:\n        return (\"Text is too short to analyze\", \"\")\n\n    pieces = [[] for _ in xrange(best_len)]\n    for i, c in enumerate(cleaned):\n        pieces[i % best_len].append(c)\n\n    freqs = [frequency(p) for p in pieces]\n\n    key = \"\"\n    for fr in freqs:\n        fr.sort(key=itemgetter(1), reverse=True)\n\n        m = 0\n        max_corr = 0.0\n        for j in xrange(nchars):\n            corr = 0.0\n            c = ordA + j\n            for frc in fr:\n                d = (ord(frc[0]) - c + nchars) % nchars\n                corr += frc[1] * target_freqs[d]\n\n            if corr > max_corr:\n                m = j\n                max_corr = corr\n\n        key += chr(m + ordA)\n\n    r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)\n         for i, c in enumerate(cleaned))\n    return (key, \"\".join(r))\n\n\ndef main():\n    encoded = \n\n    english_frequences = [\n        0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n        0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n        0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n        0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\n    (key, decoded) = vigenere_decrypt(english_frequences, encoded)\n    print \"Key:\", key\n    print \"\\nText:\", decoded\n\nmain()\n"}
{"id": 40785, "name": "Pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n", "Python": "def calcPi():\n    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n    while True:\n        if 4*q+r-t < n*t:\n            yield n\n            nr = 10*(r-n*t)\n            n  = ((10*(3*q+r))//t)-10*n\n            q  *= 10\n            r  = nr\n        else:\n            nr = (2*q+r)*l\n            nn = (q*(7*k)+2+(r*l))//(t*l)\n            q  *= k\n            t  *= l\n            l  += 2\n            k += 1\n            n  = nn\n            r  = nr\n\nimport sys\npi_digits = calcPi()\ni = 0\nfor d in pi_digits:\n    sys.stdout.write(str(d))\n    i += 1\n    if i == 40: print(\"\"); i = 0\n"}
{"id": 40786, "name": "Hofstadter Q sequence", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n"}
{"id": 40787, "name": "Hofstadter Q sequence", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n"}
{"id": 40788, "name": "Y combinator", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))\n>>> [ Y(fac)(i) for i in range(10) ]\n[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]\n>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))\n>>> [ Y(fib)(i) for i in range(10) ]\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 40789, "name": "Return multiple values", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n", "Python": "def addsub(x, y):\n  return x + y, x - y\n"}
{"id": 40790, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n"}
{"id": 40791, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n"}
{"id": 40792, "name": "FTP", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n", "Python": "from ftplib import FTP\nftp = FTP('kernel.org')\nftp.login()\nftp.cwd('/pub/linux/kernel')\nftp.set_pasv(True) \nprint ftp.retrlines('LIST')\nprint ftp.retrbinary('RETR README', open('README', 'wb').write)\nftp.quit()\n"}
{"id": 40793, "name": "24 game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n", "Python": "\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n\ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            print (\"New digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n\nif __name__ == '__main__': main()\n"}
{"id": 40794, "name": "24 game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n", "Python": "\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n\ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            print (\"New digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n\nif __name__ == '__main__': main()\n"}
{"id": 40795, "name": "24 game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n", "Python": "\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n\ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            print (\"New digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n\nif __name__ == '__main__': main()\n"}
{"id": 40796, "name": "Loops_Continue", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 10; i++ {\n        fmt.Printf(\"%d\", i)\n        if i%5 == 0 {\n            fmt.Printf(\"\\n\")\n            continue\n        }\n        fmt.Printf(\", \")\n    }\n}\n", "Python": "for i in range(1, 11):\n    if i % 5 == 0:\n        print(i)\n        continue\n    print(i, end=', ')\n"}
{"id": 40797, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "Python": "\n\n\nfrom livewires import *\n\nhoriz=640; vert=480\nbegin_graphics(width=horiz,height=vert,title=\"v_stripes\",background=Colour.black)\nNameColors=[\"black\",\"red\",\"green\",\"dark_blue\",\"purple\",\"blue\",\"yellow\",\"white\"]\nstepik=horiz/len(NameColors)\n\nfor index,each in enumerate(NameColors):\n\tExcStrng=\"set_colour(Colour.\"+each+\")\"\n\texec ExcStrng\n\tbox(index*stepik,0,(index+1)*stepik,vert,filled=1)\n\nwhile keys_pressed() != ['x']: \n\tpass\n\nend_graphics()\n"}
{"id": 40798, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "Python": "\n\n\nfrom livewires import *\n\nhoriz=640; vert=480\nbegin_graphics(width=horiz,height=vert,title=\"v_stripes\",background=Colour.black)\nNameColors=[\"black\",\"red\",\"green\",\"dark_blue\",\"purple\",\"blue\",\"yellow\",\"white\"]\nstepik=horiz/len(NameColors)\n\nfor index,each in enumerate(NameColors):\n\tExcStrng=\"set_colour(Colour.\"+each+\")\"\n\texec ExcStrng\n\tbox(index*stepik,0,(index+1)*stepik,vert,filled=1)\n\nwhile keys_pressed() != ['x']: \n\tpass\n\nend_graphics()\n"}
{"id": 40799, "name": "LU decomposition", "Go": "package main\n\nimport \"fmt\"\n    \ntype matrix [][]float64\n\nfunc zero(n int) matrix {\n    r := make([][]float64, n)\n    a := make([]float64, n*n)\n    for i := range r {\n        r[i] = a[n*i : n*(i+1)]\n    } \n    return r \n}\n    \nfunc eye(n int) matrix {\n    r := zero(n)\n    for i := range r {\n        r[i][i] = 1\n    }\n    return r\n}   \n    \nfunc (m matrix) print(label string) {\n    if label > \"\" {\n        fmt.Printf(\"%s:\\n\", label)\n    }\n    for _, r := range m {\n        for _, e := range r {\n            fmt.Printf(\" %9.5f\", e)\n        }\n        fmt.Println()\n    }\n}\n\nfunc (a matrix) pivotize() matrix { \n    p := eye(len(a))\n    for j, r := range a {\n        max := r[j] \n        row := j\n        for i := j; i < len(a); i++ {\n            if a[i][j] > max {\n                max = a[i][j]\n                row = i\n            }\n        }\n        if j != row {\n            \n            p[j], p[row] = p[row], p[j]\n        }\n    } \n    return p\n}\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    r := zero(len(m1))\n    for i, r1 := range m1 {\n        for j := range m2 {\n            for k := range m1 {\n                r[i][j] += r1[k] * m2[k][j]\n            }\n        }\n    }\n    return r\n}\n\nfunc (a matrix) lu() (l, u, p matrix) {\n    l = zero(len(a))\n    u = zero(len(a))\n    p = a.pivotize()\n    a = p.mul(a)\n    for j := range a {\n        l[j][j] = 1\n        for i := 0; i <= j; i++ {\n            sum := 0.\n            for k := 0; k < i; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            u[i][j] = a[i][j] - sum\n        }\n        for i := j; i < len(a); i++ {\n            sum := 0.\n            for k := 0; k < j; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            l[i][j] = (a[i][j] - sum) / u[j][j]\n        }\n    }\n    return\n}\n\nfunc main() {\n    showLU(matrix{\n        {1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}})\n    showLU(matrix{\n        {11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}})\n}\n\nfunc showLU(a matrix) {\n    a.print(\"\\na\")\n    l, u, p := a.lu()\n    l.print(\"l\")\n    u.print(\"u\") \n    p.print(\"p\") \n}\n", "Python": "from pprint import pprint\n\ndef matrixMul(A, B):\n    TB = zip(*B)\n    return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]\n\ndef pivotize(m):\n    \n    n = len(m)\n    ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]\n    for j in xrange(n):\n        row = max(xrange(j, n), key=lambda i: abs(m[i][j]))\n        if j != row:\n            ID[j], ID[row] = ID[row], ID[j]\n    return ID\n\ndef lu(A):\n    \n    n = len(A)\n    L = [[0.0] * n for i in xrange(n)]\n    U = [[0.0] * n for i in xrange(n)]\n    P = pivotize(A)\n    A2 = matrixMul(P, A)\n    for j in xrange(n):\n        L[j][j] = 1.0\n        for i in xrange(j+1):\n            s1 = sum(U[k][j] * L[i][k] for k in xrange(i))\n            U[i][j] = A2[i][j] - s1\n        for i in xrange(j, n):\n            s2 = sum(U[k][j] * L[i][k] for k in xrange(j))\n            L[i][j] = (A2[i][j] - s2) / U[j][j]\n    return (L, U, P)\n\na = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]\nfor part in lu(a):\n    pprint(part, width=19)\n    print\nprint\nb = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]\nfor part in lu(b):\n    pprint(part)\n    print\n"}
{"id": 40800, "name": "General FizzBuzz", "Go": "package main\n\nimport (\n\t\"fmt\"\n)\n\nconst numbers = 3\n\nfunc main() {\n\n\t\n\tmax := 20\n\twords := map[int]string{\n\t\t3: \"Fizz\",\n\t\t5: \"Buzz\",\n\t\t7: \"Baxx\",\n\t}\n\tkeys := []int{3, 5, 7}\n\tdivisible := false\n\tfor i := 1; i <= max; i++ {\n\t\tfor _, n := range keys {\n\t\t\tif i % n == 0 {\n\t\t\t\tfmt.Print(words[n])\n\t\t\t\tdivisible = true\n\t\t\t}\n\t\t}\n\t\tif !divisible {\n\t\t\tfmt.Print(i)\n\t\t}\n\t\tfmt.Println()\n\t\tdivisible = false\n\t}\n\n}\n", "Python": "def genfizzbuzz(factorwords, numbers):\n    \n    factorwords.sort(key=lambda factor_and_word: factor_and_word[0])\n    lines = []\n    for num in numbers:\n        words = ''.join(word for factor, word in factorwords if (num % factor) == 0)\n        lines.append(words if words else str(num))\n    return '\\n'.join(lines)\n\nif __name__ == '__main__':\n    print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))\n"}
{"id": 40801, "name": "Read a specific line from a file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif line, err := rsl(\"input.txt\", 7); err == nil {\n\t\tfmt.Println(\"7th line:\")\n\t\tfmt.Println(line)\n\t} else {\n\t\tfmt.Println(\"rsl:\", err)\n\t}\n}\n\nfunc rsl(fn string, n int) (string, error) {\n\tif n < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid request: line %d\", n)\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tbf := bufio.NewReader(f)\n\tvar line string\n\tfor lnum := 0; lnum < n; lnum++ {\n\t\tline, err = bf.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tswitch lnum {\n\t\t\tcase 0:\n\t\t\t\treturn \"\", errors.New(\"no lines in file\")\n\t\t\tcase 1:\n\t\t\t\treturn \"\", errors.New(\"only 1 line\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"only %d lines\", lnum)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif line == \"\" {\n\t\treturn \"\", fmt.Errorf(\"line %d empty\", n)\n\t}\n\treturn line, nil\n}\n", "Python": "with open('xxx.txt') as f:\n    for i, line in enumerate(f):\n        if i == 6:\n            break\n    else:\n        print('Not 7 lines in file')\n        line = None\n"}
{"id": 40802, "name": "Read a specific line from a file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif line, err := rsl(\"input.txt\", 7); err == nil {\n\t\tfmt.Println(\"7th line:\")\n\t\tfmt.Println(line)\n\t} else {\n\t\tfmt.Println(\"rsl:\", err)\n\t}\n}\n\nfunc rsl(fn string, n int) (string, error) {\n\tif n < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid request: line %d\", n)\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tbf := bufio.NewReader(f)\n\tvar line string\n\tfor lnum := 0; lnum < n; lnum++ {\n\t\tline, err = bf.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tswitch lnum {\n\t\t\tcase 0:\n\t\t\t\treturn \"\", errors.New(\"no lines in file\")\n\t\t\tcase 1:\n\t\t\t\treturn \"\", errors.New(\"only 1 line\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"only %d lines\", lnum)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif line == \"\" {\n\t\treturn \"\", fmt.Errorf(\"line %d empty\", n)\n\t}\n\treturn line, nil\n}\n", "Python": "with open('xxx.txt') as f:\n    for i, line in enumerate(f):\n        if i == 6:\n            break\n    else:\n        print('Not 7 lines in file')\n        line = None\n"}
{"id": 40803, "name": "Read a specific line from a file", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif line, err := rsl(\"input.txt\", 7); err == nil {\n\t\tfmt.Println(\"7th line:\")\n\t\tfmt.Println(line)\n\t} else {\n\t\tfmt.Println(\"rsl:\", err)\n\t}\n}\n\nfunc rsl(fn string, n int) (string, error) {\n\tif n < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid request: line %d\", n)\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tbf := bufio.NewReader(f)\n\tvar line string\n\tfor lnum := 0; lnum < n; lnum++ {\n\t\tline, err = bf.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tswitch lnum {\n\t\t\tcase 0:\n\t\t\t\treturn \"\", errors.New(\"no lines in file\")\n\t\t\tcase 1:\n\t\t\t\treturn \"\", errors.New(\"only 1 line\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"only %d lines\", lnum)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif line == \"\" {\n\t\treturn \"\", fmt.Errorf(\"line %d empty\", n)\n\t}\n\treturn line, nil\n}\n", "Python": "with open('xxx.txt') as f:\n    for i, line in enumerate(f):\n        if i == 6:\n            break\n    else:\n        print('Not 7 lines in file')\n        line = None\n"}
{"id": 40804, "name": "File extension is in extensions list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar extensions = []string{\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\n\nfunc fileExtInList(filename string) (bool, string) {\n    filename2 := strings.ToLower(filename)\n    for _, ext := range extensions {\n        ext2 := \".\" + strings.ToLower(ext)\n        if strings.HasSuffix(filename2, ext2) {\n            return true, ext\n        }\n    }\n    s := strings.Split(filename, \".\")\n    if len(s) > 1 {\n        t := s[len(s)-1]\n        if t != \"\" {\n            return false, t\n        } else {\n            return false, \"<empty>\"\n        }\n    } else {\n        return false, \"<none>\"\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The listed extensions are:\")\n    fmt.Println(extensions, \"\\n\")\n    tests := []string{\n        \"MyData.a##\", \"MyData.tar.Gz\", \"MyData.gzip\",\n        \"MyData.7z.backup\", \"MyData...\", \"MyData\",\n        \"MyData_v1.0.tar.bz2\", \"MyData_v1.0.bz2\",\n    }\n    for _, test := range tests {\n        ok, ext := fileExtInList(test)\n        fmt.Printf(\"%-20s => %-5t  (extension = %s)\\n\", test, ok, ext)\n    }\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 40805, "name": "File extension is in extensions list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar extensions = []string{\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\n\nfunc fileExtInList(filename string) (bool, string) {\n    filename2 := strings.ToLower(filename)\n    for _, ext := range extensions {\n        ext2 := \".\" + strings.ToLower(ext)\n        if strings.HasSuffix(filename2, ext2) {\n            return true, ext\n        }\n    }\n    s := strings.Split(filename, \".\")\n    if len(s) > 1 {\n        t := s[len(s)-1]\n        if t != \"\" {\n            return false, t\n        } else {\n            return false, \"<empty>\"\n        }\n    } else {\n        return false, \"<none>\"\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The listed extensions are:\")\n    fmt.Println(extensions, \"\\n\")\n    tests := []string{\n        \"MyData.a##\", \"MyData.tar.Gz\", \"MyData.gzip\",\n        \"MyData.7z.backup\", \"MyData...\", \"MyData\",\n        \"MyData_v1.0.tar.bz2\", \"MyData_v1.0.bz2\",\n    }\n    for _, test := range tests {\n        ok, ext := fileExtInList(test)\n        fmt.Printf(\"%-20s => %-5t  (extension = %s)\\n\", test, ok, ext)\n    }\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 40806, "name": "File extension is in extensions list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar extensions = []string{\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\n\nfunc fileExtInList(filename string) (bool, string) {\n    filename2 := strings.ToLower(filename)\n    for _, ext := range extensions {\n        ext2 := \".\" + strings.ToLower(ext)\n        if strings.HasSuffix(filename2, ext2) {\n            return true, ext\n        }\n    }\n    s := strings.Split(filename, \".\")\n    if len(s) > 1 {\n        t := s[len(s)-1]\n        if t != \"\" {\n            return false, t\n        } else {\n            return false, \"<empty>\"\n        }\n    } else {\n        return false, \"<none>\"\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The listed extensions are:\")\n    fmt.Println(extensions, \"\\n\")\n    tests := []string{\n        \"MyData.a##\", \"MyData.tar.Gz\", \"MyData.gzip\",\n        \"MyData.7z.backup\", \"MyData...\", \"MyData\",\n        \"MyData_v1.0.tar.bz2\", \"MyData_v1.0.bz2\",\n    }\n    for _, test := range tests {\n        ok, ext := fileExtInList(test)\n        fmt.Printf(\"%-20s => %-5t  (extension = %s)\\n\", test, ok, ext)\n    }\n}\n", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n"}
{"id": 40807, "name": "24 game_Solve", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nconst (\n\top_num = iota\n\top_add\n\top_sub\n\top_mul\n\top_div\n)\n\ntype frac struct {\n\tnum, denom int\n}\n\n\n\ntype Expr struct {\n\top          int\n\tleft, right *Expr\n\tvalue       frac\n}\n\nvar n_cards = 4\nvar goal = 24\nvar digit_range = 9\n\nfunc (x *Expr) String() string {\n\tif x.op == op_num {\n\t\treturn fmt.Sprintf(\"%d\", x.value.num)\n\t}\n\n\tvar bl1, br1, bl2, br2, opstr string\n\tswitch {\n\tcase x.left.op == op_num:\n\tcase x.left.op >= x.op:\n\tcase x.left.op == op_add && x.op == op_sub:\n\t\tbl1, br1 = \"\", \"\"\n\tdefault:\n\t\tbl1, br1 = \"(\", \")\"\n\t}\n\n\tif x.right.op == op_num || x.op < x.right.op {\n\t\tbl2, br2 = \"\", \"\"\n\t} else {\n\t\tbl2, br2 = \"(\", \")\"\n\t}\n\n\tswitch {\n\tcase x.op == op_add:\n\t\topstr = \" + \"\n\tcase x.op == op_sub:\n\t\topstr = \" - \"\n\tcase x.op == op_mul:\n\t\topstr = \" * \"\n\tcase x.op == op_div:\n\t\topstr = \" / \"\n\t}\n\n\treturn bl1 + x.left.String() + br1 + opstr +\n\t\tbl2 + x.right.String() + br2\n}\n\nfunc expr_eval(x *Expr) (f frac) {\n\tif x.op == op_num {\n\t\treturn x.value\n\t}\n\n\tl, r := expr_eval(x.left), expr_eval(x.right)\n\n\tswitch x.op {\n\tcase op_add:\n\t\tf.num = l.num*r.denom + l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_sub:\n\t\tf.num = l.num*r.denom - l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_mul:\n\t\tf.num = l.num * r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_div:\n\t\tf.num = l.num * r.denom\n\t\tf.denom = l.denom * r.num\n\t\treturn\n\t}\n\treturn\n}\n\nfunc solve(ex_in []*Expr) bool {\n\t\n\t\n\tif len(ex_in) == 1 {\n\t\tf := expr_eval(ex_in[0])\n\t\tif f.denom != 0 && f.num == f.denom*goal {\n\t\t\tfmt.Println(ex_in[0].String())\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tvar node Expr\n\tex := make([]*Expr, len(ex_in)-1)\n\n\t\n\t\n\tfor i := range ex {\n\t\tcopy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])\n\n\t\tex[i] = &node\n\t\tfor j := i + 1; j < len(ex_in); j++ {\n\t\t\tnode.left = ex_in[i]\n\t\t\tnode.right = ex_in[j]\n\n\t\t\t\n\t\t\tfor o := op_add; o <= op_div; o++ {\n\t\t\t\tnode.op = o\n\t\t\t\tif solve(ex) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\n\t\t\tnode.left = ex_in[j]\n\t\t\tnode.right = ex_in[i]\n\n\t\t\tnode.op = op_sub\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tnode.op = op_div\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif j < len(ex) {\n\t\t\t\tex[j] = ex_in[j]\n\t\t\t}\n\t\t}\n\t\tex[i] = ex_in[i]\n\t}\n\treturn false\n}\n\nfunc main() {\n\tcards := make([]*Expr, n_cards)\n\trand.Seed(time.Now().Unix())\n\n\tfor k := 0; k < 10; k++ {\n\t\tfor i := 0; i < n_cards; i++ {\n\t\t\tcards[i] = &Expr{op_num, nil, nil,\n\t\t\t\tfrac{rand.Intn(digit_range-1) + 1, 1}}\n\t\t\tfmt.Printf(\" %d\", cards[i].value.num)\n\t\t}\n\t\tfmt.Print(\":  \")\n\t\tif !solve(cards) {\n\t\t\tfmt.Println(\"No solution\")\n\t\t}\n\t}\n}\n", "Python": "\n \nfrom   __future__ import division, print_function\nfrom   itertools  import permutations, combinations, product, \\\n                         chain\nfrom   pprint     import pprint as pp\nfrom   fractions  import Fraction as F\nimport random, ast, re\nimport sys\n \nif sys.version_info[0] < 3:\n    input = raw_input\n    from itertools import izip_longest as zip_longest\nelse:\n    from itertools import zip_longest\n \n \ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n \ndef ask4():\n    'get four random digits >0 from the player'\n    digits = ''\n    while len(digits) != 4 or not all(d in '123456789' for d in digits):\n        digits = input('Enter the digits to solve for: ')\n        digits = ''.join(digits.strip().split())\n    return list(digits)\n \ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n \ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n \ndef solve(digits):\n    \n    digilen = len(digits)\n    \n    exprlen = 2 * digilen - 1\n    \n    digiperm = sorted(set(permutations(digits)))\n    \n    opcomb   = list(product('+-*/', repeat=digilen-1))\n    \n    brackets = ( [()] + [(x,y)\n                         for x in range(0, exprlen, 2)\n                         for y in range(x+4, exprlen+2, 2)\n                         if (x,y) != (0,exprlen+1)]\n                 + [(0, 3+1, 4+2, 7+3)] ) \n    for d in digiperm:\n        for ops in opcomb:\n            if '/' in ops:\n                d2 = [('F(%s)' % i) for i in d] \n            else:\n                d2 = d\n            ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))\n            for b in brackets:\n                exp = ex[::]\n                for insertpoint, bracket in zip(b, '()'*(len(b)//2)):\n                    exp.insert(insertpoint, bracket)\n                txt = ''.join(exp)\n                try:\n                    num = eval(txt)\n                except ZeroDivisionError:\n                    continue\n                if num == 24:\n                    if '/' in ops:\n                        exp = [ (term if not term.startswith('F(') else term[2])\n                               for term in exp ]\n                    ans = ' '.join(exp).rstrip()\n                    print (\"Solution found:\",ans)\n                    return ans\n    print (\"No solution found for:\", ' '.join(digits))            \n    return '!'\n \ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer == '?':\n            solve(digits)\n            answer = '!'\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if answer == '!!':\n            digits = ask4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            if '/' in answer:\n                \n                answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)\n                                  for char in answer )\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n \nmain()\n"}
{"id": 40808, "name": "24 game_Solve", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nconst (\n\top_num = iota\n\top_add\n\top_sub\n\top_mul\n\top_div\n)\n\ntype frac struct {\n\tnum, denom int\n}\n\n\n\ntype Expr struct {\n\top          int\n\tleft, right *Expr\n\tvalue       frac\n}\n\nvar n_cards = 4\nvar goal = 24\nvar digit_range = 9\n\nfunc (x *Expr) String() string {\n\tif x.op == op_num {\n\t\treturn fmt.Sprintf(\"%d\", x.value.num)\n\t}\n\n\tvar bl1, br1, bl2, br2, opstr string\n\tswitch {\n\tcase x.left.op == op_num:\n\tcase x.left.op >= x.op:\n\tcase x.left.op == op_add && x.op == op_sub:\n\t\tbl1, br1 = \"\", \"\"\n\tdefault:\n\t\tbl1, br1 = \"(\", \")\"\n\t}\n\n\tif x.right.op == op_num || x.op < x.right.op {\n\t\tbl2, br2 = \"\", \"\"\n\t} else {\n\t\tbl2, br2 = \"(\", \")\"\n\t}\n\n\tswitch {\n\tcase x.op == op_add:\n\t\topstr = \" + \"\n\tcase x.op == op_sub:\n\t\topstr = \" - \"\n\tcase x.op == op_mul:\n\t\topstr = \" * \"\n\tcase x.op == op_div:\n\t\topstr = \" / \"\n\t}\n\n\treturn bl1 + x.left.String() + br1 + opstr +\n\t\tbl2 + x.right.String() + br2\n}\n\nfunc expr_eval(x *Expr) (f frac) {\n\tif x.op == op_num {\n\t\treturn x.value\n\t}\n\n\tl, r := expr_eval(x.left), expr_eval(x.right)\n\n\tswitch x.op {\n\tcase op_add:\n\t\tf.num = l.num*r.denom + l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_sub:\n\t\tf.num = l.num*r.denom - l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_mul:\n\t\tf.num = l.num * r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_div:\n\t\tf.num = l.num * r.denom\n\t\tf.denom = l.denom * r.num\n\t\treturn\n\t}\n\treturn\n}\n\nfunc solve(ex_in []*Expr) bool {\n\t\n\t\n\tif len(ex_in) == 1 {\n\t\tf := expr_eval(ex_in[0])\n\t\tif f.denom != 0 && f.num == f.denom*goal {\n\t\t\tfmt.Println(ex_in[0].String())\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tvar node Expr\n\tex := make([]*Expr, len(ex_in)-1)\n\n\t\n\t\n\tfor i := range ex {\n\t\tcopy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])\n\n\t\tex[i] = &node\n\t\tfor j := i + 1; j < len(ex_in); j++ {\n\t\t\tnode.left = ex_in[i]\n\t\t\tnode.right = ex_in[j]\n\n\t\t\t\n\t\t\tfor o := op_add; o <= op_div; o++ {\n\t\t\t\tnode.op = o\n\t\t\t\tif solve(ex) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\n\t\t\tnode.left = ex_in[j]\n\t\t\tnode.right = ex_in[i]\n\n\t\t\tnode.op = op_sub\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tnode.op = op_div\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif j < len(ex) {\n\t\t\t\tex[j] = ex_in[j]\n\t\t\t}\n\t\t}\n\t\tex[i] = ex_in[i]\n\t}\n\treturn false\n}\n\nfunc main() {\n\tcards := make([]*Expr, n_cards)\n\trand.Seed(time.Now().Unix())\n\n\tfor k := 0; k < 10; k++ {\n\t\tfor i := 0; i < n_cards; i++ {\n\t\t\tcards[i] = &Expr{op_num, nil, nil,\n\t\t\t\tfrac{rand.Intn(digit_range-1) + 1, 1}}\n\t\t\tfmt.Printf(\" %d\", cards[i].value.num)\n\t\t}\n\t\tfmt.Print(\":  \")\n\t\tif !solve(cards) {\n\t\t\tfmt.Println(\"No solution\")\n\t\t}\n\t}\n}\n", "Python": "\n \nfrom   __future__ import division, print_function\nfrom   itertools  import permutations, combinations, product, \\\n                         chain\nfrom   pprint     import pprint as pp\nfrom   fractions  import Fraction as F\nimport random, ast, re\nimport sys\n \nif sys.version_info[0] < 3:\n    input = raw_input\n    from itertools import izip_longest as zip_longest\nelse:\n    from itertools import zip_longest\n \n \ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n \ndef ask4():\n    'get four random digits >0 from the player'\n    digits = ''\n    while len(digits) != 4 or not all(d in '123456789' for d in digits):\n        digits = input('Enter the digits to solve for: ')\n        digits = ''.join(digits.strip().split())\n    return list(digits)\n \ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n \ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n \ndef solve(digits):\n    \n    digilen = len(digits)\n    \n    exprlen = 2 * digilen - 1\n    \n    digiperm = sorted(set(permutations(digits)))\n    \n    opcomb   = list(product('+-*/', repeat=digilen-1))\n    \n    brackets = ( [()] + [(x,y)\n                         for x in range(0, exprlen, 2)\n                         for y in range(x+4, exprlen+2, 2)\n                         if (x,y) != (0,exprlen+1)]\n                 + [(0, 3+1, 4+2, 7+3)] ) \n    for d in digiperm:\n        for ops in opcomb:\n            if '/' in ops:\n                d2 = [('F(%s)' % i) for i in d] \n            else:\n                d2 = d\n            ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))\n            for b in brackets:\n                exp = ex[::]\n                for insertpoint, bracket in zip(b, '()'*(len(b)//2)):\n                    exp.insert(insertpoint, bracket)\n                txt = ''.join(exp)\n                try:\n                    num = eval(txt)\n                except ZeroDivisionError:\n                    continue\n                if num == 24:\n                    if '/' in ops:\n                        exp = [ (term if not term.startswith('F(') else term[2])\n                               for term in exp ]\n                    ans = ' '.join(exp).rstrip()\n                    print (\"Solution found:\",ans)\n                    return ans\n    print (\"No solution found for:\", ' '.join(digits))            \n    return '!'\n \ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer == '?':\n            solve(digits)\n            answer = '!'\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if answer == '!!':\n            digits = ask4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            if '/' in answer:\n                \n                answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)\n                                  for char in answer )\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n \nmain()\n"}
{"id": 40809, "name": "Checkpoint synchronization", "Go": "package main\n  \nimport (\n    \"log\"\n    \"math/rand\"\n    \"sync\"\n    \"time\"\n)\n\nfunc worker(part string) {\n    log.Println(part, \"worker begins part\")\n    time.Sleep(time.Duration(rand.Int63n(1e6)))\n    log.Println(part, \"worker completes part\")\n    wg.Done()\n}\n\nvar (\n    partList    = []string{\"A\", \"B\", \"C\", \"D\"}\n    nAssemblies = 3\n    wg          sync.WaitGroup\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for c := 1; c <= nAssemblies; c++ {\n        log.Println(\"begin assembly cycle\", c)\n        wg.Add(len(partList))\n        for _, part := range partList {\n            go worker(part)\n        }\n        wg.Wait()\n        log.Println(\"assemble.  cycle\", c, \"complete\")\n    }\n}\n", "Python": "\n\nimport threading\nimport time\nimport random\n\n\ndef worker(workernum, barrier):\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 1, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n    barrier.wait()\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 2, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n\nbarrier = threading.Barrier(3)\n\nw1 = threading.Thread(target=worker, args=((1,barrier)))\nw2 = threading.Thread(target=worker, args=((2,barrier)))\nw3 = threading.Thread(target=worker, args=((3,barrier)))\n\nw1.start()\nw2.start()\nw3.start()\n"}
{"id": 40810, "name": "Checkpoint synchronization", "Go": "package main\n  \nimport (\n    \"log\"\n    \"math/rand\"\n    \"sync\"\n    \"time\"\n)\n\nfunc worker(part string) {\n    log.Println(part, \"worker begins part\")\n    time.Sleep(time.Duration(rand.Int63n(1e6)))\n    log.Println(part, \"worker completes part\")\n    wg.Done()\n}\n\nvar (\n    partList    = []string{\"A\", \"B\", \"C\", \"D\"}\n    nAssemblies = 3\n    wg          sync.WaitGroup\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for c := 1; c <= nAssemblies; c++ {\n        log.Println(\"begin assembly cycle\", c)\n        wg.Add(len(partList))\n        for _, part := range partList {\n            go worker(part)\n        }\n        wg.Wait()\n        log.Println(\"assemble.  cycle\", c, \"complete\")\n    }\n}\n", "Python": "\n\nimport threading\nimport time\nimport random\n\n\ndef worker(workernum, barrier):\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 1, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n    barrier.wait()\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 2, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n\nbarrier = threading.Barrier(3)\n\nw1 = threading.Thread(target=worker, args=((1,barrier)))\nw2 = threading.Thread(target=worker, args=((2,barrier)))\nw3 = threading.Thread(target=worker, args=((3,barrier)))\n\nw1.start()\nw2.start()\nw3.start()\n"}
{"id": 40811, "name": "Variable-length quantity", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"encoding/binary\"\n)\n\nfunc main() {\n    buf := make([]byte, binary.MaxVarintLen64)\n    for _, x := range []int64{0x200000, 0x1fffff} {\n        v := buf[:binary.PutVarint(buf, x)]\n        fmt.Printf(\"%d encodes into %d bytes: %x\\n\", x, len(v), v)\n        x, _ = binary.Varint(v)\n        fmt.Println(x, \"decoded\")\n    }\n}\n", "Python": "def tobits(n, _group=8, _sep='_', _pad=False):\n    'Express n as binary bits with separator'\n    bits = '{0:b}'.format(n)[::-1]\n    if _pad:\n        bits = '{0:0{1}b}'.format(n,\n                                  ((_group+len(bits)-1)//_group)*_group)[::-1]\n        answer = _sep.join(bits[i:i+_group]\n                                 for i in range(0, len(bits), _group))[::-1]\n        answer = '0'*(len(_sep)-1) + answer\n    else:\n        answer = _sep.join(bits[i:i+_group]\n                           for i in range(0, len(bits), _group))[::-1]\n    return answer\n\ndef tovlq(n):\n    return tobits(n, _group=7, _sep='1_', _pad=True)\n\ndef toint(vlq):\n    return int(''.join(vlq.split('_1')), 2)    \n\ndef vlqsend(vlq):\n    for i, byte in enumerate(vlq.split('_')[::-1]):\n        print('Sent byte {0:3}: {1:\n"}
{"id": 40812, "name": "Record sound", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    name := \"\"\n    for name == \"\" {\n        fmt.Print(\"Enter output file name (without extension) : \")\n        scanner.Scan()\n        name = scanner.Text()\n        check(scanner.Err())\n    }\n    name += \".wav\"\n\n    rate := 0\n    for rate < 2000 || rate > 192000 {\n        fmt.Print(\"Enter sampling rate in Hz (2000 to 192000) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        rate, _ = strconv.Atoi(input)\n    }\n    rateS := strconv.Itoa(rate)\n\n    dur := 0.0\n    for dur < 5 || dur > 30 {\n        fmt.Print(\"Enter duration in seconds (5 to 30)        : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        dur, _ = strconv.ParseFloat(input, 64)\n    }\n    durS := strconv.FormatFloat(dur, 'f', -1, 64)\n\n    fmt.Println(\"OK, start speaking now...\")\n    \n    args := []string{\"-r\", rateS, \"-f\", \"S16_LE\", \"-d\", durS, name}\n    cmd := exec.Command(\"arecord\", args...)\n    err := cmd.Run()\n    check(err)\n\n    fmt.Printf(\"'%s' created on disk and will now be played back...\\n\", name)\n    cmd = exec.Command(\"aplay\", name)\n    err = cmd.Run()\n    check(err)\n    fmt.Println(\"Play-back completed.\")\n}\n", "Python": "import pyaudio\n\nchunk = 1024\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 44100\n\np = pyaudio.PyAudio()\n\nstream = p.open(format = FORMAT,\n                channels = CHANNELS,\n                rate = RATE,\n                input = True,\n                frames_per_buffer = chunk)\n\ndata = stream.read(chunk)\nprint [ord(i) for i in data]\n"}
{"id": 40813, "name": "SHA-256 Merkle tree", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"os\"\n)\n\nfunc main() {\n    const blockSize = 1024\n    f, err := os.Open(\"title.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n\n    var hashes [][]byte\n    buffer := make([]byte, blockSize)\n    h := sha256.New()\n    for {\n        bytesRead, err := f.Read(buffer)\n        if err != nil {\n            if err != io.EOF {\n                log.Fatal(err)\n            }\n            break\n        }\n        h.Reset()\n        h.Write(buffer[:bytesRead])\n        hashes = append(hashes, h.Sum(nil))\n    }\n    buffer = make([]byte, 64)\n    for len(hashes) > 1 {\n        var hashes2 [][]byte\n        for i := 0; i < len(hashes); i += 2 {\n            if i < len(hashes)-1 {                \n                copy(buffer, hashes[i])\n                copy(buffer[32:], hashes[i+1])\n                h.Reset()\n                h.Write(buffer)\n                hashes2 = append(hashes2, h.Sum(nil))\n            } else {\n                hashes2 = append(hashes2, hashes[i])\n            }\n        }\n        hashes = hashes2\n    }\n    fmt.Printf(\"%x\", hashes[0])\n    fmt.Println()\n}\n", "Python": "\n\n\nimport argh\nimport hashlib  \nimport sys\n  \n@argh.arg('filename', nargs='?', default=None)\ndef main(filename, block_size=1024*1024):\n    if filename:\n        fin = open(filename, 'rb')\n    else: \n        fin = sys.stdin\n    \n    stack = []\n    block = fin.read(block_size)\n    while block:\n        \n        node = (0, hashlib.sha256(block).digest())\n        stack.append(node)\n\n        \n        while len(stack) >= 2 and stack[-2][0] == stack[-1][0]:\n            a = stack[-2]\n            b = stack[-1]\n            l = a[0]\n            stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())]\n\n        block = fin.read(block_size)\n    \n    while len(stack) > 1:\n        \n        a = stack[-2]\n        b = stack[-1]\n        al = a[0]\n        bl = b[0]\n        stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())]\n\n    print(stack[0][1].hex())\n\n\nargh.dispatch_command(main)\n"}
{"id": 40814, "name": "String case", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    show(\"alphaBETA\")\n    show(\"alpha BETA\")\n    \n    show(\"Ǆǈǌ\")\n    \n    show(\"o'hare O'HARE o’hare don't\")\n}\n\nfunc show(s string) {\n    fmt.Println(\"\\nstring:         \",\n        s, \" len:\", utf8.RuneCountInString(s), \"runes\") \n    fmt.Println(\"All upper case: \", strings.ToUpper(s)) \n    fmt.Println(\"All lower case: \", strings.ToLower(s)) \n    fmt.Println(\"All title case: \", strings.ToTitle(s)) \n    fmt.Println(\"Title words:    \", strings.Title(s))   \n    fmt.Println(\"Swapping case:  \",                     \n        strings.Map(unicode.SimpleFold, s))\n}\n", "Python": "s = \"alphaBETA\"\nprint s.upper() \nprint s.lower() \n\nprint s.swapcase() \n\nprint \"fOo bAR\".capitalize() \nprint \"fOo bAR\".title() \n\nimport string\nprint string.capwords(\"fOo bAR\") \n"}
{"id": 40815, "name": "User input_Graphical", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"math/rand\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc validateInput(window *gtk.Window, str1, str2 string) bool {\n    n, err := strconv.ParseFloat(str2, 64)\n    if len(str1) == 0 || err != nil || n != 75000 {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid input\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return false\n    }\n    return true\n}\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetTitle(\"Rosetta Code\")\n    window.SetPosition(gtk.WIN_POS_CENTER)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)\n    check(err, \"Unable to create vertical box:\")\n    vbox.SetBorderWidth(1)\n\n    hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create first horizontal box:\")\n\n    hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create second horizontal box:\")\n\n    label, err := gtk.LabelNew(\"Enter a string and the number 75000   \\n\")\n    check(err, \"Unable to create label:\")\n\n    sel, err := gtk.LabelNew(\"String:      \")\n    check(err, \"Unable to create string entry label:\")\n\n    nel, err := gtk.LabelNew(\"Number: \")\n    check(err, \"Unable to create number entry label:\")\n\n    se, err := gtk.EntryNew()\n    check(err, \"Unable to create string entry:\")\n\n    ne, err := gtk.EntryNew()\n    check(err, \"Unable to create number entry:\")\n\n    hbox1.PackStart(sel, false, false, 2)\n    hbox1.PackStart(se, false, false, 2)\n\n    hbox2.PackStart(nel, false, false, 2)\n    hbox2.PackStart(ne, false, false, 2)\n\n    \n    ab, err := gtk.ButtonNewWithLabel(\"Accept\")\n    check(err, \"Unable to create accept button:\")\n    ab.Connect(\"clicked\", func() {\n        \n        str1, _ := se.GetText()\n        str2, _ := ne.GetText()\n        if validateInput(window, str1, str2) {\n            window.Destroy() \n        }\n    })\n\n    vbox.Add(label)\n    vbox.Add(hbox1)\n    vbox.Add(hbox2)\n    vbox.Add(ab)\n    window.Add(vbox)\n\n    window.ShowAll()\n    gtk.Main()\n}\n", "Python": "from javax.swing import JOptionPane\n\ndef to_int(n, default=0):\n    try:\n        return int(n)\n    except ValueError:\n        return default\n\nnumber = to_int(JOptionPane.showInputDialog (\"Enter an Integer\")) \nprintln(number)\n\na_string = JOptionPane.showInputDialog (\"Enter a String\")\nprintln(a_string)\n"}
{"id": 40816, "name": "Sierpinski arrowhead curve", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n    iy     = 1.0\n    theta  = 0\n)\n\nvar cx, cy, h float64\n\nfunc arrowhead(order int, length float64) {\n    \n    if order&1 == 0 {\n        curve(order, length, 60)\n    } else {\n        turn(60)\n        curve(order, length, -60)\n    }\n    drawLine(length) \n}\n\nfunc drawLine(length float64) {\n    dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h)\n    rads := gg.Radians(float64(theta))\n    cx += length * math.Cos(rads)\n    cy += length * math.Sin(rads)\n}\n\nfunc turn(angle int) {\n    theta = (theta + angle) % 360\n}\n\nfunc curve(order int, length float64, angle int) {\n    if order == 0 {\n        drawLine(length)\n    } else {\n        curve(order-1, length/2, -angle)\n        turn(angle)\n        curve(order-1, length/2, angle)\n        turn(angle)\n        curve(order-1, length/2, -angle)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    order := 6\n    if order&1 == 0 {\n        iy = -1 \n    }\n    cx, cy = width/2, height\n    h = cx / 2\n    arrowhead(order, cx)\n    dc.SetRGB255(255, 0, 255) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_arrowhead_curve.png\")\n}\n", "Python": "t = { 'x': 20, 'y': 30, 'a': 60 }\n\ndef setup():\n    size(450, 400)\n    background(0, 0, 200)\n    stroke(-1)\n    sc(7, 400, -60)\n\ndef sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5):\n    if o:\n        o -= 1\n        l *= HALF\n        sc(o, l, -a)[A] += a\n        sc(o, l, a)[A] += a\n        sc(o, l, -a)\n    else:\n        x, y = s[X], s[Y]\n        s[X] += cos(radians(s[A])) * l\n        s[Y] += sin(radians(s[A])) * l\n        line(x, y, s[X], s[Y])\n\n    return s\n"}
{"id": 40817, "name": "Text processing_1", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tfilename = \"readings.txt\"\n\treadings = 24             \n\tfields   = readings*2 + 1 \n)\n\nfunc main() {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\tvar (\n\t\tbadRun, maxRun   int\n\t\tbadDate, maxDate string\n\t\tfileSum          float64\n\t\tfileAccept       int\n\t)\n\tendBadRun := func() {\n\t\tif badRun > maxRun {\n\t\t\tmaxRun = badRun\n\t\t\tmaxDate = badDate\n\t\t}\n\t\tbadRun = 0\n\t}\n\ts := bufio.NewScanner(file)\n\tfor s.Scan() {\n\t\tf := strings.Fields(s.Text())\n\t\tif len(f) != fields {\n\t\t\tlog.Fatal(\"unexpected format,\", len(f), \"fields.\")\n\t\t}\n\t\tvar accept int\n\t\tvar sum float64\n\t\tfor i := 1; i < fields; i += 2 {\n\t\t\tflag, err := strconv.Atoi(f[i+1])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tif flag <= 0 { \n\t\t\t\tif badRun++; badRun == 1 {\n\t\t\t\t\tbadDate = f[0]\n\t\t\t\t}\n\t\t\t} else { \n\t\t\t\tendBadRun()\n\t\t\t\tvalue, err := strconv.ParseFloat(f[i], 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tsum += value\n\t\t\t\taccept++\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Line: %s  Reject %2d  Accept: %2d  Line_tot:%9.3f\",\n\t\t\tf[0], readings-accept, accept, sum)\n\t\tif accept > 0 {\n\t\t\tfmt.Printf(\"  Line_avg:%8.3f\\n\", sum/float64(accept))\n\t\t} else {\n\t\t\tfmt.Println()\n\t\t}\n\t\tfileSum += sum\n\t\tfileAccept += accept\n\t}\n\tif err := s.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tendBadRun()\n\n\tfmt.Println(\"\\nFile     =\", filename)\n\tfmt.Printf(\"Total    = %.3f\\n\", fileSum)\n\tfmt.Println(\"Readings = \", fileAccept)\n\tif fileAccept > 0 {\n\t\tfmt.Printf(\"Average  =  %.3f\\n\", fileSum/float64(fileAccept))\n\t}\n\tif maxRun == 0 {\n\t\tfmt.Println(\"\\nAll data valid.\")\n\t} else {\n\t\tfmt.Printf(\"\\nMax data gap = %d, beginning on line %s.\\n\",\n\t\t\tmaxRun, maxDate)\n\t}\n}\n", "Python": "import fileinput\nimport sys\n\nnodata = 0;             \nnodata_max=-1;          \nnodata_maxline=[];      \n\ntot_file = 0            \nnum_file = 0            \n\ninfiles = sys.argv[1:]\n\nfor line in fileinput.input():\n  tot_line=0;             \n  num_line=0;             \n\n  \n  field = line.split()\n  date  = field[0]\n  data  = [float(f) for f in field[1::2]]\n  flags = [int(f)   for f in field[2::2]]\n\n  for datum, flag in zip(data, flags):\n    if flag<1:\n      nodata += 1\n    else:\n      \n      if nodata_max==nodata and nodata>0:\n        nodata_maxline.append(date)\n      if nodata_max<nodata and nodata>0:\n        nodata_max=nodata\n        nodata_maxline=[date]\n      \n      nodata=0; \n      \n      tot_line += datum\n      num_line += 1\n\n  \n  tot_file += tot_line\n  num_file += num_line\n\n  print \"Line: %11s  Reject: %2i  Accept: %2i  Line_tot: %10.3f  Line_avg: %10.3f\" % (\n        date, \n        len(data) -num_line, \n        num_line, tot_line, \n        tot_line/num_line if (num_line>0) else 0)\n\nprint \"\"\nprint \"File(s)  = %s\" % (\", \".join(infiles),)\nprint \"Total    = %10.3f\" % (tot_file,)\nprint \"Readings = %6i\" % (num_file,)\nprint \"Average  = %10.3f\" % (tot_file / num_file,)\n\nprint \"\\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s\" % (\n    nodata_max, \", \".join(nodata_maxline))\n"}
{"id": 40818, "name": "MD5", "Go": "package main\n\nimport (\n    \"crypto/md5\"\n    \"fmt\"\n)\n\nfunc main() {\n    for _, p := range [][2]string{\n        \n        {\"d41d8cd98f00b204e9800998ecf8427e\", \"\"},\n        {\"0cc175b9c0f1b6a831c399e269772661\", \"a\"},\n        {\"900150983cd24fb0d6963f7d28e17f72\", \"abc\"},\n        {\"f96b697d7cb7938d525a2f31aaf161d0\", \"message digest\"},\n        {\"c3fcd3d76192e4007dfb496cca67e13b\", \"abcdefghijklmnopqrstuvwxyz\"},\n        {\"d174ab98d277d9f5a5611c2c9f419d9f\",\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"},\n        {\"57edf4a22be3c955ac49da2e2107b67a\", \"12345678901234567890\" +\n            \"123456789012345678901234567890123456789012345678901234567890\"},\n        \n        {\"e38ca1d920c4b8b8d3946b2c72f01680\",\n            \"The quick brown fox jumped over the lazy dog's back\"},\n    } {\n        validate(p[0], p[1])\n    }\n}\n\nvar h = md5.New()\n\nfunc validate(check, s string) {\n    h.Reset()\n    h.Write([]byte(s))\n    sum := fmt.Sprintf(\"%x\", h.Sum(nil))\n    if sum != check {\n        fmt.Println(\"MD5 fail\")\n        fmt.Println(\"  for string,\", s)\n        fmt.Println(\"  expected:  \", check)\n        fmt.Println(\"  got:       \", sum)\n    }\n}\n", "Python": ">>> import hashlib\n>>> \n>>> tests = (\n  (b\"\", 'd41d8cd98f00b204e9800998ecf8427e'),\n  (b\"a\", '0cc175b9c0f1b6a831c399e269772661'),\n  (b\"abc\", '900150983cd24fb0d6963f7d28e17f72'),\n  (b\"message digest\", 'f96b697d7cb7938d525a2f31aaf161d0'),\n  (b\"abcdefghijklmnopqrstuvwxyz\", 'c3fcd3d76192e4007dfb496cca67e13b'),\n  (b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", 'd174ab98d277d9f5a5611c2c9f419d9f'),\n  (b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\", '57edf4a22be3c955ac49da2e2107b67a') )\n>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden\n\n>>>\n"}
{"id": 40819, "name": "Aliquot sequence classifications", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nconst threshold = uint64(1) << 47\n\nfunc indexOf(s []uint64, search uint64) int {\n    for i, e := range s {\n        if e == search {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc contains(s []uint64, search uint64) bool {\n    return indexOf(s, search) > -1\n}\n\nfunc maxOf(i1, i2 int) int {\n    if i1 > i2 {\n        return i1\n    }\n    return i2\n}\n\nfunc sumProperDivisors(n uint64) uint64 {\n    if n < 2 {\n        return 0\n    }\n    sqrt := uint64(math.Sqrt(float64(n)))\n    sum := uint64(1)\n    for i := uint64(2); i <= sqrt; i++ {\n        if n % i != 0 {\n            continue\n        }\n        sum += i + n / i\n    }\n    if sqrt * sqrt == n {\n        sum -= sqrt\n    }\n    return sum\n}\n\nfunc classifySequence(k uint64) ([]uint64, string) {\n    if k == 0 {\n        panic(\"Argument must be positive.\")\n    }\n    last := k\n    var seq []uint64\n    seq = append(seq, k)\n    for {\n        last = sumProperDivisors(last)\n        seq = append(seq, last)\n        n := len(seq)\n        aliquot := \"\"\n        switch {\n        case last == 0:\n            aliquot = \"Terminating\"\n        case n == 2 && last == k:\n            aliquot = \"Perfect\"\n        case n == 3 && last == k:\n            aliquot = \"Amicable\"\n        case n >= 4 && last == k:\n            aliquot = fmt.Sprintf(\"Sociable[%d]\", n - 1)\n        case last == seq[n - 2]:\n            aliquot = \"Aspiring\"\n        case contains(seq[1 : maxOf(1, n - 2)], last):\n            aliquot = fmt.Sprintf(\"Cyclic[%d]\", n - 1 - indexOf(seq[:], last))\n        case n == 16 || last > threshold:\n            aliquot = \"Non-Terminating\"\n        }\n        if aliquot != \"\" {\n            return seq, aliquot\n        }\n    }\n}\n\nfunc joinWithCommas(seq []uint64) string {\n    res := fmt.Sprint(seq)\n    res = strings.Replace(res, \" \", \", \", -1)\n    return res\n}\n\nfunc main() {\n    fmt.Println(\"Aliquot classifications - periods for Sociable/Cyclic in square brackets:\\n\")\n    for k := uint64(1); k <= 10; k++ {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%2d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    s := []uint64{\n        11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,\n    }\n    for _, k := range s {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%7d: %-15s %s\\n\",  k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    k := uint64(15355717786080)\n    seq, aliquot := classifySequence(k)\n    fmt.Printf(\"%d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n}\n", "Python": "from proper_divisors import proper_divs\nfrom functools import lru_cache\n\n\n@lru_cache()\ndef pdsum(n): \n    return sum(proper_divs(n))\n    \n    \ndef aliquot(n, maxlen=16, maxterm=2**47):\n    if n == 0:\n        return 'terminating', [0]\n    s, slen, new = [n], 1, n\n    while slen <= maxlen and new < maxterm:\n        new = pdsum(s[-1])\n        if new in s:\n            if s[0] == new:\n                if slen == 1:\n                    return 'perfect', s\n                elif slen == 2:\n                    return 'amicable', s\n                else:\n                    return 'sociable of length %i' % slen, s\n            elif s[-1] == new:\n                return 'aspiring', s\n            else:\n                return 'cyclic back to %i' % new, s\n        elif new == 0:\n            return 'terminating', s + [0]\n        else:\n            s.append(new)\n            slen += 1\n    else:\n        return 'non-terminating', s\n                \nif __name__ == '__main__':\n    for n in range(1, 11): \n        print('%s: %r' % aliquot(n))\n    print()\n    for n in [11, 12, 28, 496, 220, 1184,  12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: \n        print('%s: %r' % aliquot(n))\n"}
{"id": 40820, "name": "Aliquot sequence classifications", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nconst threshold = uint64(1) << 47\n\nfunc indexOf(s []uint64, search uint64) int {\n    for i, e := range s {\n        if e == search {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc contains(s []uint64, search uint64) bool {\n    return indexOf(s, search) > -1\n}\n\nfunc maxOf(i1, i2 int) int {\n    if i1 > i2 {\n        return i1\n    }\n    return i2\n}\n\nfunc sumProperDivisors(n uint64) uint64 {\n    if n < 2 {\n        return 0\n    }\n    sqrt := uint64(math.Sqrt(float64(n)))\n    sum := uint64(1)\n    for i := uint64(2); i <= sqrt; i++ {\n        if n % i != 0 {\n            continue\n        }\n        sum += i + n / i\n    }\n    if sqrt * sqrt == n {\n        sum -= sqrt\n    }\n    return sum\n}\n\nfunc classifySequence(k uint64) ([]uint64, string) {\n    if k == 0 {\n        panic(\"Argument must be positive.\")\n    }\n    last := k\n    var seq []uint64\n    seq = append(seq, k)\n    for {\n        last = sumProperDivisors(last)\n        seq = append(seq, last)\n        n := len(seq)\n        aliquot := \"\"\n        switch {\n        case last == 0:\n            aliquot = \"Terminating\"\n        case n == 2 && last == k:\n            aliquot = \"Perfect\"\n        case n == 3 && last == k:\n            aliquot = \"Amicable\"\n        case n >= 4 && last == k:\n            aliquot = fmt.Sprintf(\"Sociable[%d]\", n - 1)\n        case last == seq[n - 2]:\n            aliquot = \"Aspiring\"\n        case contains(seq[1 : maxOf(1, n - 2)], last):\n            aliquot = fmt.Sprintf(\"Cyclic[%d]\", n - 1 - indexOf(seq[:], last))\n        case n == 16 || last > threshold:\n            aliquot = \"Non-Terminating\"\n        }\n        if aliquot != \"\" {\n            return seq, aliquot\n        }\n    }\n}\n\nfunc joinWithCommas(seq []uint64) string {\n    res := fmt.Sprint(seq)\n    res = strings.Replace(res, \" \", \", \", -1)\n    return res\n}\n\nfunc main() {\n    fmt.Println(\"Aliquot classifications - periods for Sociable/Cyclic in square brackets:\\n\")\n    for k := uint64(1); k <= 10; k++ {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%2d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    s := []uint64{\n        11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,\n    }\n    for _, k := range s {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%7d: %-15s %s\\n\",  k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    k := uint64(15355717786080)\n    seq, aliquot := classifySequence(k)\n    fmt.Printf(\"%d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n}\n", "Python": "from proper_divisors import proper_divs\nfrom functools import lru_cache\n\n\n@lru_cache()\ndef pdsum(n): \n    return sum(proper_divs(n))\n    \n    \ndef aliquot(n, maxlen=16, maxterm=2**47):\n    if n == 0:\n        return 'terminating', [0]\n    s, slen, new = [n], 1, n\n    while slen <= maxlen and new < maxterm:\n        new = pdsum(s[-1])\n        if new in s:\n            if s[0] == new:\n                if slen == 1:\n                    return 'perfect', s\n                elif slen == 2:\n                    return 'amicable', s\n                else:\n                    return 'sociable of length %i' % slen, s\n            elif s[-1] == new:\n                return 'aspiring', s\n            else:\n                return 'cyclic back to %i' % new, s\n        elif new == 0:\n            return 'terminating', s + [0]\n        else:\n            s.append(new)\n            slen += 1\n    else:\n        return 'non-terminating', s\n                \nif __name__ == '__main__':\n    for n in range(1, 11): \n        print('%s: %r' % aliquot(n))\n    print()\n    for n in [11, 12, 28, 496, 220, 1184,  12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: \n        print('%s: %r' % aliquot(n))\n"}
{"id": 40821, "name": "Date manipulation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nconst taskDate = \"March 7 2009 7:30pm EST\"\nconst taskFormat = \"January 2 2006 3:04pm MST\"\n\nfunc main() {\n    if etz, err := time.LoadLocation(\"US/Eastern\"); err == nil {\n        time.Local = etz\n    }\n    fmt.Println(\"Input:             \", taskDate)\n    t, err := time.Parse(taskFormat, taskDate)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    t = t.Add(12 * time.Hour)\n    fmt.Println(\"+12 hrs:           \", t)\n    if _, offset := t.Zone(); offset == 0 {\n        fmt.Println(\"No time zone info.\")\n        return\n    }\n    atz, err := time.LoadLocation(\"US/Arizona\")\n    if err == nil {\n        fmt.Println(\"+12 hrs in Arizona:\", t.In(atz))\n    }\n}\n", "Python": "import datetime\n\ndef mt():\n\tdatime1=\"March 7 2009 7:30pm EST\"\n\tformatting = \"%B %d %Y %I:%M%p \"\n\tdatime2 = datime1[:-3]  \n\ttdelta = datetime.timedelta(hours=12)\t\t\n\ts3 = datetime.datetime.strptime(datime2, formatting)\n\tdatime2 = s3+tdelta\n\tprint datime2.strftime(\"%B %d %Y %I:%M%p %Z\") + datime1[-3:]\n\nmt()\n"}
{"id": 40822, "name": "Sorting algorithms_Sleep sort", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc main() {\n\tout := make(chan uint64)\n\tfor _, a := range os.Args[1:] {\n\t\ti, err := strconv.ParseUint(a, 10, 64)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tgo func(n uint64) {\n\t\t\ttime.Sleep(time.Duration(n) * time.Millisecond)\n\t\t\tout <- n\n\t\t}(i)\n\t}\n\tfor _ = range os.Args[1:] {\n\t\tfmt.Println(<-out)\n\t}\n}\n", "Python": "from time import sleep\nfrom threading import Timer\n\ndef sleepsort(values):\n    sleepsort.result = []\n    def add1(x):\n        sleepsort.result.append(x)\n    mx = values[0]\n    for v in values:\n        if mx < v: mx = v\n        Timer(v, add1, [v]).start()\n    sleep(mx+1)\n    return sleepsort.result\n\nif __name__ == '__main__':\n    x = [3,2,4,7,3,6,9,1]\n    if sleepsort(x) == sorted(x):\n        print('sleep sort worked for:',x)\n    else:\n        print('sleep sort FAILED for:',x)\n"}
{"id": 40823, "name": "Loops_Nested", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    values := make([][]int, 10)\n    for i := range values {\n        values[i] = make([]int, 10)\n        for j := range values[i] {\n            values[i][j] = rand.Intn(20) + 1\n        }\n    }\n\nouterLoop:\n    for i, row := range values {\n        fmt.Printf(\"%3d)\", i)\n        for _, value := range row {\n            fmt.Printf(\" %3d\", value)\n            if value == 20 {\n                break outerLoop\n            }\n        }\n        fmt.Printf(\"\\n\")\n    }\n    fmt.Printf(\"\\n\")\n}\n", "Python": "from random import randint\n\ndef do_scan(mat):\n    for row in mat:\n        for item in row:\n            print item,\n            if item == 20:\n                print\n                return\n        print\n    print\n\nmat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]\ndo_scan(mat)\n"}
{"id": 40824, "name": "Pythagorean triples", "Go": "package main\n\nimport \"fmt\"\n\nvar total, prim, maxPeri int64\n\nfunc newTri(s0, s1, s2 int64) {\n    if p := s0 + s1 + s2; p <= maxPeri {\n        prim++\n        total += maxPeri / p\n        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)\n        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)\n        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)\n    }\n}\n\nfunc main() {\n    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {\n        prim = 0\n        total = 0\n        newTri(3, 4, 5)\n        fmt.Printf(\"Up to %d:  %d triples, %d primitives\\n\",\n            maxPeri, total, prim)\n    }\n}\n", "Python": "from fractions import gcd\n\n\ndef pt1(maxperimeter=100):\n    \n    trips = []\n    for a in range(1, maxperimeter):\n        aa = a*a\n        for b in range(a, maxperimeter-a+1):\n            bb = b*b\n            for c in range(b, maxperimeter-b-a+1):\n                cc = c*c\n                if a+b+c > maxperimeter or cc > aa + bb: break\n                if aa + bb == cc:\n                    trips.append((a,b,c, gcd(a, b) == 1))\n    return trips\n\ndef pytrip(trip=(3,4,5),perim=100, prim=1):\n    a0, b0, c0 = a, b, c = sorted(trip)\n    t, firstprim = set(), prim>0\n    while a + b + c <= perim:\n        t.add((a, b, c, firstprim>0))\n        a, b, c, firstprim = a+a0, b+b0, c+c0, False\n    \n    t2 = set()\n    for a, b, c, firstprim in t:\n        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7\n        if  a5 - b5 + c7 <= perim:\n            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)\n        if  a5 + b5 + c7 <= perim:\n            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)\n        if -a5 + b5 + c7 <= perim:\n            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)\n    return t | t2\n\ndef pt2(maxperimeter=100):\n    \n    trips = pytrip((3,4,5), maxperimeter, 1)\n    return trips\n\ndef printit(maxperimeter=100, pt=pt1):\n    trips = pt(maxperimeter)\n    print(\"  Up to a perimeter of %i there are %i triples, of which %i are primitive\"\n          % (maxperimeter,\n             len(trips),\n             len([prim for a,b,c,prim in trips if prim])))\n  \nfor algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):\n    print(algo.__doc__)\n    for maxperimeter in range(mn, mx+1, mn):\n        printit(maxperimeter, algo)\n"}
{"id": 40825, "name": "Pythagorean triples", "Go": "package main\n\nimport \"fmt\"\n\nvar total, prim, maxPeri int64\n\nfunc newTri(s0, s1, s2 int64) {\n    if p := s0 + s1 + s2; p <= maxPeri {\n        prim++\n        total += maxPeri / p\n        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)\n        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)\n        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)\n    }\n}\n\nfunc main() {\n    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {\n        prim = 0\n        total = 0\n        newTri(3, 4, 5)\n        fmt.Printf(\"Up to %d:  %d triples, %d primitives\\n\",\n            maxPeri, total, prim)\n    }\n}\n", "Python": "from fractions import gcd\n\n\ndef pt1(maxperimeter=100):\n    \n    trips = []\n    for a in range(1, maxperimeter):\n        aa = a*a\n        for b in range(a, maxperimeter-a+1):\n            bb = b*b\n            for c in range(b, maxperimeter-b-a+1):\n                cc = c*c\n                if a+b+c > maxperimeter or cc > aa + bb: break\n                if aa + bb == cc:\n                    trips.append((a,b,c, gcd(a, b) == 1))\n    return trips\n\ndef pytrip(trip=(3,4,5),perim=100, prim=1):\n    a0, b0, c0 = a, b, c = sorted(trip)\n    t, firstprim = set(), prim>0\n    while a + b + c <= perim:\n        t.add((a, b, c, firstprim>0))\n        a, b, c, firstprim = a+a0, b+b0, c+c0, False\n    \n    t2 = set()\n    for a, b, c, firstprim in t:\n        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7\n        if  a5 - b5 + c7 <= perim:\n            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)\n        if  a5 + b5 + c7 <= perim:\n            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)\n        if -a5 + b5 + c7 <= perim:\n            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)\n    return t | t2\n\ndef pt2(maxperimeter=100):\n    \n    trips = pytrip((3,4,5), maxperimeter, 1)\n    return trips\n\ndef printit(maxperimeter=100, pt=pt1):\n    trips = pt(maxperimeter)\n    print(\"  Up to a perimeter of %i there are %i triples, of which %i are primitive\"\n          % (maxperimeter,\n             len(trips),\n             len([prim for a,b,c,prim in trips if prim])))\n  \nfor algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):\n    print(algo.__doc__)\n    for maxperimeter in range(mn, mx+1, mn):\n        printit(maxperimeter, algo)\n"}
{"id": 40826, "name": "Remove duplicate elements", "Go": "package main\n\nimport \"fmt\"\n\nfunc uniq(list []int) []int {\n\tunique_set := make(map[int]bool, len(list))\n\tfor _, x := range list {\n\t\tunique_set[x] = true\n\t}\n\tresult := make([]int, 0, len(unique_set))\n\tfor x := range unique_set {\n\t\tresult = append(result, x)\n\t}\n\treturn result\n}\n\nfunc main() {\n\tfmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) \n}\n", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n"}
{"id": 40827, "name": "Look-and-say sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc lss(s string) (r string) {\n    c := s[0]\n    nc := 1\n    for i := 1; i < len(s); i++ {\n        d := s[i]\n        if d == c {\n            nc++\n            continue\n        }\n        r += strconv.Itoa(nc) + string(c)\n        c = d\n        nc = 1\n    }\n    return r + strconv.Itoa(nc) + string(c)\n}\n\nfunc main() {\n    s := \"1\"\n    fmt.Println(s)\n    for i := 0; i < 8; i++ {\n        s = lss(s)\n        fmt.Println(s)\n    }\n}\n", "Python": "def lookandsay(number):\n    result = \"\"\n\n    repeat = number[0]\n    number = number[1:]+\" \"\n    times = 1\n\n    for actual in number:\n        if actual != repeat:\n            result += str(times)+repeat\n            times = 1\n            repeat = actual\n        else:\n            times += 1\n\n    return result\n\nnum = \"1\"\n\nfor i in range(10):\n    print num\n    num = lookandsay(num)\n"}
{"id": 40828, "name": "Totient function", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(\" n  phi   prime\")\n    fmt.Println(\"---------------\")\n    count := 0\n    for n := 1; n <= 25; n++ {\n        tot := totient(n)\n        isPrime := n-1 == tot\n        if isPrime {\n            count++\n        }\n        fmt.Printf(\"%2d   %2d   %t\\n\", n, tot, isPrime)\n    }\n    fmt.Println(\"\\nNumber of primes up to 25     =\", count)\n    for n := 26; n <= 100000; n++ {\n        tot := totient(n)\n        if tot == n-1 {\n            count++\n        }\n        if n == 100 || n == 1000 || n%10000 == 0 {\n            fmt.Printf(\"\\nNumber of primes up to %-6d = %d\\n\", n, count)\n        }\n    }\n}\n", "Python": "from math import gcd\n\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\nif __name__ == '__main__':\n    def is_prime(n):\n        return φ(n) == n - 1\n    \n    for n in range(1, 26):\n        print(f\" φ({n}) == {φ(n)}{', is prime' if is_prime(n)  else ''}\")\n    count = 0\n    for n in range(1, 10_000 + 1):\n        count += is_prime(n)\n        if n in {100, 1000, 10_000}:\n            print(f\"Primes up to {n}: {count}\")\n"}
{"id": 40829, "name": "Conditional structures", "Go": "if booleanExpression {\n    statements\n}\n", "Python": "if x == 0:\n    foo()\nelif x == 1:\n    bar()\nelif x == 2:\n    baz()\nelse:\n    qux()\n\nmatch x:\n    0 => foo()\n    1 => bar()\n    2 => baz()\n    _ => qux()\n\n(a) ? b : c\n"}
{"id": 40830, "name": "Fractran", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc compile(src string) ([]big.Rat, bool) {\n    s := strings.Fields(src)\n    r := make([]big.Rat, len(s))\n    for i, s1 := range s {\n        if _, ok := r[i].SetString(s1); !ok {\n            return nil, false\n        }\n    }\n    return r, true\n}\n\nfunc exec(p []big.Rat, n *big.Int, limit int) {\n    var q, r big.Int\nrule:\n    for i := 0; i < limit; i++ {\n        fmt.Printf(\"%d \", n)\n        for j := range p {\n            q.QuoRem(n, p[j].Denom(), &r)\n            if r.BitLen() == 0 {\n                n.Mul(&q, p[j].Num())\n                continue rule\n            }\n        }\n        break\n    }\n    fmt.Println()\n}\n\nfunc usage() {\n    log.Fatal(\"usage: ft <limit> <n> <prog>\")\n}\n\nfunc main() {\n    if len(os.Args) != 4 {\n        usage()\n    }\n    limit, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        usage()\n    }\n    var n big.Int\n    _, ok := n.SetString(os.Args[2], 10)\n    if !ok {\n        usage()\n    }\n    p, ok := compile(os.Args[3])\n    if !ok {\n        usage()\n    }\n    exec(p, &n, limit)\n}\n", "Python": "from fractions import Fraction\n\ndef fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'\n                        '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'\n                        '13 / 11, 15 / 14, 15 / 2, 55 / 1'):\n    flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]\n\n    n = Fraction(n)\n    while True:\n        yield n.numerator\n        for f in flist:\n            if (n * f).denominator == 1:\n                break\n        else:\n            break\n        n *= f\n    \nif __name__ == '__main__':\n    n, m = 2, 15\n    print('First %i members of fractran(%i):\\n  ' % (m, n) +\n          ', '.join(str(f) for f,i in zip(fractran(n), range(m))))\n"}
{"id": 40831, "name": "Sorting algorithms_Stooge sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    stoogesort(a)\n    fmt.Println(\"after: \", a)\n    fmt.Println(\"nyuk nyuk nyuk\")\n}\n\nfunc stoogesort(a []int) {\n    last := len(a) - 1\n    if a[last] < a[0] {\n        a[0], a[last] = a[last], a[0]\n    }\n    if last > 1 {\n        t := len(a) / 3\n        stoogesort(a[:len(a)-t])\n        stoogesort(a[t:])\n        stoogesort(a[:len(a)-t])\n    }\n}\n", "Python": ">>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]\n>>> def stoogesort(L, i=0, j=None):\n\tif j is None:\n\t\tj = len(L) - 1\n\tif L[j] < L[i]:\n\t\tL[i], L[j] = L[j], L[i]\n\tif j - i > 1:\n\t\tt = (j - i + 1) // 3\n\t\tstoogesort(L, i  , j-t)\n\t\tstoogesort(L, i+t, j  )\n\t\tstoogesort(L, i  , j-t)\n\treturn L\n\n>>> stoogesort(data)\n[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]\n"}
{"id": 40832, "name": "Galton box animation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst boxW = 41      \nconst boxH = 37      \nconst pinsBaseW = 19 \nconst nMaxBalls = 55 \n\nconst centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1\n\nconst (\n    empty  = ' '\n    ball   = 'o'\n    wall   = '|'\n    corner = '+'\n    floor  = '-'\n    pin    = '.'\n)\n\ntype Ball struct{ x, y int }\n\nfunc newBall(x, y int) *Ball {\n    if box[y][x] != empty {\n        panic(\"Tried to create a new ball in a non-empty cell. Program terminated.\")\n    }\n    b := Ball{x, y}\n    box[y][x] = ball\n    return &b\n}\n\nfunc (b *Ball) doStep() {\n    if b.y <= 0 {\n        return \n    }\n    cell := box[b.y-1][b.x]\n    switch cell {\n    case empty:\n        box[b.y][b.x] = empty\n        b.y--\n        box[b.y][b.x] = ball\n    case pin:\n        box[b.y][b.x] = empty\n        b.y--\n        if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty {\n            b.x += rand.Intn(2)*2 - 1\n            box[b.y][b.x] = ball\n            return\n        } else if box[b.y][b.x-1] == empty {\n            b.x++\n        } else {\n            b.x--\n        }\n        box[b.y][b.x] = ball\n    default:\n        \n    }\n}\n\ntype Cell = byte\n\n\nvar box [boxH][boxW]Cell\n\nfunc initializeBox() {\n    \n    box[0][0] = corner\n    box[0][boxW-1] = corner\n    for i := 1; i < boxW-1; i++ {\n        box[0][i] = floor\n    }\n    for i := 0; i < boxW; i++ {\n        box[boxH-1][i] = box[0][i]\n    }\n\n    \n    for r := 1; r < boxH-1; r++ {\n        box[r][0] = wall\n        box[r][boxW-1] = wall\n    }\n\n    \n    for i := 1; i < boxH-1; i++ {\n        for j := 1; j < boxW-1; j++ {\n            box[i][j] = empty\n        }\n    }\n\n    \n    for nPins := 1; nPins <= pinsBaseW; nPins++ {\n        for p := 0; p < nPins; p++ {\n            box[boxH-2-nPins][centerH+1-nPins+p*2] = pin\n        }\n    }\n}\n\nfunc drawBox() {\n    for r := boxH - 1; r >= 0; r-- {\n        for c := 0; c < boxW; c++ {\n            fmt.Printf(\"%c\", box[r][c])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initializeBox()\n    var balls []*Ball\n    for i := 0; i < nMaxBalls+boxH; i++ {\n        fmt.Println(\"\\nStep\", i, \":\")\n        if i < nMaxBalls {\n            balls = append(balls, newBall(centerH, boxH-2)) \n        }\n        drawBox()\n\n        \n        \n        for _, b := range balls {\n            b.doStep()\n        }\n    }\n}\n", "Python": "\n\nimport sys, os\nimport random\nimport time\n\ndef print_there(x, y, text):\n     sys.stdout.write(\"\\x1b7\\x1b[%d;%df%s\\x1b8\" % (x, y, text))\n     sys.stdout.flush()\n\n\nclass Ball():\n    def __init__(self):\n        self.x = 0\n        self.y = 0\n        \n    def update(self):\n        self.x += random.randint(0,1)\n        self.y += 1\n\n    def fall(self):\n        self.y +=1\n\n\nclass Board():\n    def __init__(self, width, well_depth, N):\n        self.balls = []\n        self.fallen = [0] * (width + 1)\n        self.width = width\n        self.well_depth = well_depth\n        self.N = N\n        self.shift = 4\n        \n    def update(self):\n        for ball in self.balls:\n            if ball.y < self.width:\n                ball.update()\n            elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:\n                ball.fall()\n            elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:\n                self.fallen[ball.x] += 1\n            else:\n                pass\n                \n    def balls_on_board(self):\n        return len(self.balls) - sum(self.fallen)\n                \n    def add_ball(self):\n        if(len(self.balls) <= self.N):\n            self.balls.append(Ball())\n\n    def print_board(self):\n        for y in range(self.width + 1):\n            for x in range(y):\n                print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, \"\n    def print_ball(self, ball):\n        if ball.y <= self.width:\n            x = self.width - ball.y + 2*ball.x + self.shift\n        else:\n            x = 2*ball.x + self.shift\n        y = ball.y + 1\n        print_there(y, x, \"*\")\n         \n    def print_all(self):\n        print(chr(27) + \"[2J\")\n        self.print_board();\n        for ball in self.balls:\n            self.print_ball(ball)\n\n\ndef main():\n    board = Board(width = 15, well_depth = 5, N = 10)\n    board.add_ball() \n    while(board.balls_on_board() > 0):\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.add_ball()\n\n\nif __name__==\"__main__\":\n    main()\n"}
{"id": 40833, "name": "Galton box animation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst boxW = 41      \nconst boxH = 37      \nconst pinsBaseW = 19 \nconst nMaxBalls = 55 \n\nconst centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1\n\nconst (\n    empty  = ' '\n    ball   = 'o'\n    wall   = '|'\n    corner = '+'\n    floor  = '-'\n    pin    = '.'\n)\n\ntype Ball struct{ x, y int }\n\nfunc newBall(x, y int) *Ball {\n    if box[y][x] != empty {\n        panic(\"Tried to create a new ball in a non-empty cell. Program terminated.\")\n    }\n    b := Ball{x, y}\n    box[y][x] = ball\n    return &b\n}\n\nfunc (b *Ball) doStep() {\n    if b.y <= 0 {\n        return \n    }\n    cell := box[b.y-1][b.x]\n    switch cell {\n    case empty:\n        box[b.y][b.x] = empty\n        b.y--\n        box[b.y][b.x] = ball\n    case pin:\n        box[b.y][b.x] = empty\n        b.y--\n        if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty {\n            b.x += rand.Intn(2)*2 - 1\n            box[b.y][b.x] = ball\n            return\n        } else if box[b.y][b.x-1] == empty {\n            b.x++\n        } else {\n            b.x--\n        }\n        box[b.y][b.x] = ball\n    default:\n        \n    }\n}\n\ntype Cell = byte\n\n\nvar box [boxH][boxW]Cell\n\nfunc initializeBox() {\n    \n    box[0][0] = corner\n    box[0][boxW-1] = corner\n    for i := 1; i < boxW-1; i++ {\n        box[0][i] = floor\n    }\n    for i := 0; i < boxW; i++ {\n        box[boxH-1][i] = box[0][i]\n    }\n\n    \n    for r := 1; r < boxH-1; r++ {\n        box[r][0] = wall\n        box[r][boxW-1] = wall\n    }\n\n    \n    for i := 1; i < boxH-1; i++ {\n        for j := 1; j < boxW-1; j++ {\n            box[i][j] = empty\n        }\n    }\n\n    \n    for nPins := 1; nPins <= pinsBaseW; nPins++ {\n        for p := 0; p < nPins; p++ {\n            box[boxH-2-nPins][centerH+1-nPins+p*2] = pin\n        }\n    }\n}\n\nfunc drawBox() {\n    for r := boxH - 1; r >= 0; r-- {\n        for c := 0; c < boxW; c++ {\n            fmt.Printf(\"%c\", box[r][c])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initializeBox()\n    var balls []*Ball\n    for i := 0; i < nMaxBalls+boxH; i++ {\n        fmt.Println(\"\\nStep\", i, \":\")\n        if i < nMaxBalls {\n            balls = append(balls, newBall(centerH, boxH-2)) \n        }\n        drawBox()\n\n        \n        \n        for _, b := range balls {\n            b.doStep()\n        }\n    }\n}\n", "Python": "\n\nimport sys, os\nimport random\nimport time\n\ndef print_there(x, y, text):\n     sys.stdout.write(\"\\x1b7\\x1b[%d;%df%s\\x1b8\" % (x, y, text))\n     sys.stdout.flush()\n\n\nclass Ball():\n    def __init__(self):\n        self.x = 0\n        self.y = 0\n        \n    def update(self):\n        self.x += random.randint(0,1)\n        self.y += 1\n\n    def fall(self):\n        self.y +=1\n\n\nclass Board():\n    def __init__(self, width, well_depth, N):\n        self.balls = []\n        self.fallen = [0] * (width + 1)\n        self.width = width\n        self.well_depth = well_depth\n        self.N = N\n        self.shift = 4\n        \n    def update(self):\n        for ball in self.balls:\n            if ball.y < self.width:\n                ball.update()\n            elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:\n                ball.fall()\n            elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:\n                self.fallen[ball.x] += 1\n            else:\n                pass\n                \n    def balls_on_board(self):\n        return len(self.balls) - sum(self.fallen)\n                \n    def add_ball(self):\n        if(len(self.balls) <= self.N):\n            self.balls.append(Ball())\n\n    def print_board(self):\n        for y in range(self.width + 1):\n            for x in range(y):\n                print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, \"\n    def print_ball(self, ball):\n        if ball.y <= self.width:\n            x = self.width - ball.y + 2*ball.x + self.shift\n        else:\n            x = 2*ball.x + self.shift\n        y = ball.y + 1\n        print_there(y, x, \"*\")\n         \n    def print_all(self):\n        print(chr(27) + \"[2J\")\n        self.print_board();\n        for ball in self.balls:\n            self.print_ball(ball)\n\n\ndef main():\n    board = Board(width = 15, well_depth = 5, N = 10)\n    board.add_ball() \n    while(board.balls_on_board() > 0):\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.add_ball()\n\n\nif __name__==\"__main__\":\n    main()\n"}
{"id": 40834, "name": "Sorting Algorithms_Circle Sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc circleSort(a []int, lo, hi, swaps int) int {\n    if lo == hi {\n        return swaps\n    }\n    high, low := hi, lo\n    mid := (hi - lo) / 2\n    for lo < hi {\n        if a[lo] > a[hi] {\n            a[lo], a[hi] = a[hi], a[lo]\n            swaps++\n        }\n        lo++\n        hi--\n    }\n    if lo == hi {\n        if a[lo] > a[hi+1] {\n            a[lo], a[hi+1] = a[hi+1], a[lo]\n            swaps++\n        }\n    }\n    swaps = circleSort(a, low, low+mid, swaps)\n    swaps = circleSort(a, low+mid+1, high, swaps)\n    return swaps\n}\n\nfunc main() {\n    aa := [][]int{\n        {6, 7, 8, 9, 2, 5, 3, 4, 1},\n        {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},\n    }\n    for _, a := range aa {\n        fmt.Printf(\"Original: %v\\n\", a)\n        for circleSort(a, 0, len(a)-1, 0) != 0 {\n            \n        }\n        fmt.Printf(\"Sorted  : %v\\n\\n\", a)\n    }\n}\n", "Python": "\n\n\n\n\ndef circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':\n    \n    n = R-L\n    if n < 2:\n        return 0\n    swaps = 0\n    m = n//2\n    for i in range(m):\n        if A[R-(i+1)] < A[L+i]:\n            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)\n            swaps += 1\n    if (n & 1) and (A[L+m] < A[L+m-1]):\n        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)\n        swaps += 1\n    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)\n\ndef circle_sort(L:list)->'sort A in place, returning the number of swaps':\n    swaps = 0\n    s = 1\n    while s:\n        s = circle_sort_backend(L, 0, len(L))\n        swaps += s\n    return swaps\n\n\nif __name__ == '__main__':\n    from random import shuffle\n    for i in range(309):\n        L = list(range(i))\n        M = L[:]\n        shuffle(L)\n        N = L[:]\n        circle_sort(L)\n        if L != M:\n            print(len(L))\n            print(N)\n            print(L)\n"}
{"id": 40835, "name": "Sorting Algorithms_Circle Sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc circleSort(a []int, lo, hi, swaps int) int {\n    if lo == hi {\n        return swaps\n    }\n    high, low := hi, lo\n    mid := (hi - lo) / 2\n    for lo < hi {\n        if a[lo] > a[hi] {\n            a[lo], a[hi] = a[hi], a[lo]\n            swaps++\n        }\n        lo++\n        hi--\n    }\n    if lo == hi {\n        if a[lo] > a[hi+1] {\n            a[lo], a[hi+1] = a[hi+1], a[lo]\n            swaps++\n        }\n    }\n    swaps = circleSort(a, low, low+mid, swaps)\n    swaps = circleSort(a, low+mid+1, high, swaps)\n    return swaps\n}\n\nfunc main() {\n    aa := [][]int{\n        {6, 7, 8, 9, 2, 5, 3, 4, 1},\n        {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},\n    }\n    for _, a := range aa {\n        fmt.Printf(\"Original: %v\\n\", a)\n        for circleSort(a, 0, len(a)-1, 0) != 0 {\n            \n        }\n        fmt.Printf(\"Sorted  : %v\\n\\n\", a)\n    }\n}\n", "Python": "\n\n\n\n\ndef circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':\n    \n    n = R-L\n    if n < 2:\n        return 0\n    swaps = 0\n    m = n//2\n    for i in range(m):\n        if A[R-(i+1)] < A[L+i]:\n            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)\n            swaps += 1\n    if (n & 1) and (A[L+m] < A[L+m-1]):\n        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)\n        swaps += 1\n    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)\n\ndef circle_sort(L:list)->'sort A in place, returning the number of swaps':\n    swaps = 0\n    s = 1\n    while s:\n        s = circle_sort_backend(L, 0, len(L))\n        swaps += s\n    return swaps\n\n\nif __name__ == '__main__':\n    from random import shuffle\n    for i in range(309):\n        L = list(range(i))\n        M = L[:]\n        shuffle(L)\n        N = L[:]\n        circle_sort(L)\n        if L != M:\n            print(len(L))\n            print(N)\n            print(L)\n"}
{"id": 40836, "name": "Kronecker product based fractals", "Go": "package main\n\nimport \"fmt\"\n\ntype matrix [][]int\n\nfunc (m1 matrix) kroneckerProduct(m2 matrix) matrix {\n    m := len(m1)\n    n := len(m1[0])\n    p := len(m2)\n    q := len(m2[0])\n    rtn := m * p\n    ctn := n * q\n    r := make(matrix, rtn)\n    for i := range r {\n        r[i] = make([]int, ctn) \n    }\n    for i := 0; i < m; i++ {\n        for j := 0; j < n; j++ {\n            for k := 0; k < p; k++ {\n                for l := 0; l < q; l++ {\n                    r[p*i+k][q*j+l] = m1[i][j] * m2[k][l]\n                }\n            }\n        }\n    }\n    return r\n}\n\nfunc (m matrix) kroneckerPower(n int) matrix {\n    pow := m\n    for i := 1; i < n; i++ {\n        pow = pow.kroneckerProduct(m)\n    }\n    return pow\n}\n\nfunc (m matrix) print(text string) {\n    fmt.Println(text, \"fractal :\\n\")\n    for i := range m {\n        for j := range m[0] {\n            if m[i][j] == 1 {\n                fmt.Print(\"*\")\n            } else {\n                fmt.Print(\" \")\n            }\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}\n    m1.kroneckerPower(4).print(\"Vivsek\")\n\n    m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}\n    m2.kroneckerPower(4).print(\"Sierpinski carpet\")\n}\n", "Python": "import os\nfrom PIL import Image\n\n\ndef imgsave(path, arr):\n    w, h = len(arr), len(arr[0])\n    img = Image.new('1', (w, h))\n    for x in range(w):\n        for y in range(h):\n            img.putpixel((x, y), arr[x][y])\n    img.save(path)\n\n\ndef get_shape(mat):\n    return len(mat), len(mat[0])\n\n\ndef kron(matrix1, matrix2):\n    \n    final_list = []\n\n    count = len(matrix2)\n\n    for elem1 in matrix1:\n        for i in range(count):\n            sub_list = []\n            for num1 in elem1:\n                for num2 in matrix2[i]:\n                    sub_list.append(num1 * num2)\n            final_list.append(sub_list)\n\n    return final_list\n\n\ndef kronpow(mat):\n    \n    matrix = mat\n    while True:\n        yield matrix\n        matrix = kron(mat, matrix)\n\n\ndef fractal(name, mat, order=6):\n    \n    path = os.path.join('fractals', name)\n    os.makedirs(path, exist_ok=True)\n\n    fgen = kronpow(mat)\n    print(name)\n    for i in range(order):\n        p = os.path.join(path, f'{i}.jpg')\n        print('Calculating n =', i, end='\\t', flush=True)\n\n        mat = next(fgen)\n        imgsave(p, mat)\n\n        x, y = get_shape(mat)\n        print('Saved as', x, 'x', y, 'image', p)\n\n\ntest1 = [\n    [0, 1, 0],\n    [1, 1, 1],\n    [0, 1, 0]\n]\n\ntest2 = [\n    [1, 1, 1],\n    [1, 0, 1],\n    [1, 1, 1]\n]\n\ntest3 = [\n    [1, 0, 1],\n    [0, 1, 0],\n    [1, 0, 1]\n]\n\nfractal('test1', test1)\nfractal('test2', test2)\nfractal('test3', test3)\n"}
{"id": 40837, "name": "Read a configuration file", "Go": "package config\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"strings\"\n\t\"io/ioutil\"\n)\n\nvar (\n\tENONE    = errors.New(\"Requested value does not exist\")\n\tEBADTYPE = errors.New(\"Requested type and actual type do not match\")\n\tEBADVAL  = errors.New(\"Value and type do not match\")\n)\n\ntype varError struct {\n\terr error\n\tn   string\n\tt   VarType\n}\n\nfunc (err *varError) Error() string {\n\treturn fmt.Sprintf(\"%v: (%q, %v)\", err.err, err.n, err.t)\n}\n\ntype VarType int\n\nconst (\n\tBool VarType = 1 + iota\n\tArray\n\tString\n)\n\nfunc (t VarType) String() string {\n\tswitch t {\n\tcase Bool:\n\t\treturn \"Bool\"\n\tcase Array:\n\t\treturn \"Array\"\n\tcase String:\n\t\treturn \"String\"\n\t}\n\n\tpanic(\"Unknown VarType\")\n}\n\ntype confvar struct {\n\tType VarType\n\tVal  interface{}\n}\n\ntype Config struct {\n\tm map[string]confvar\n}\n\nfunc Parse(r io.Reader) (c *Config, err error) {\n\tc = new(Config)\n\tc.m = make(map[string]confvar)\n\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlines := bytes.Split(buf, []byte{'\\n'})\n\n\tfor _, line := range lines {\n\t\tline = bytes.TrimSpace(line)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch line[0] {\n\t\tcase '#', ';':\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := bytes.SplitN(line, []byte{' '}, 2)\n\t\tnam := string(bytes.ToLower(parts[0]))\n\n\t\tif len(parts) == 1 {\n\t\t\tc.m[nam] = confvar{Bool, true}\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(string(parts[1]), \",\") {\n\t\t\ttmpB := bytes.Split(parts[1], []byte{','})\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpB[i] = bytes.TrimSpace(tmpB[i])\n\t\t\t}\n\t\t\ttmpS := make([]string, 0, len(tmpB))\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpS = append(tmpS, string(tmpB[i]))\n\t\t\t}\n\n\t\t\tc.m[nam] = confvar{Array, tmpS}\n\t\t\tcontinue\n\t\t}\n\n\t\tc.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))}\n\t}\n\n\treturn\n}\n\nfunc (c *Config) Bool(name string) (bool, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn false, nil\n\t}\n\n\tif c.m[name].Type != Bool {\n\t\treturn false, &varError{EBADTYPE, name, Bool}\n\t}\n\n\tv, ok := c.m[name].Val.(bool)\n\tif !ok {\n\t\treturn false, &varError{EBADVAL, name, Bool}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) Array(name string) ([]string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn nil, &varError{ENONE, name, Array}\n\t}\n\n\tif c.m[name].Type != Array {\n\t\treturn nil, &varError{EBADTYPE, name, Array}\n\t}\n\n\tv, ok := c.m[name].Val.([]string)\n\tif !ok {\n\t\treturn nil, &varError{EBADVAL, name, Array}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) String(name string) (string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn \"\", &varError{ENONE, name, String}\n\t}\n\n\tif c.m[name].Type != String {\n\t\treturn \"\", &varError{EBADTYPE, name, String}\n\t}\n\n\tv, ok := c.m[name].Val.(string)\n\tif !ok {\n\t\treturn \"\", &varError{EBADVAL, name, String}\n\t}\n\n\treturn v, nil\n}\n", "Python": "def readconf(fn):\n    ret = {}\n    with file(fn) as fp:\n        for line in fp:\n            \n            line = line.strip()\n            if not line or line.startswith('\n            \n            boolval = True\n            \n            if line.startswith(';'):\n                \n                line = line.lstrip(';')\n                \n                if len(line.split()) != 1: continue\n                boolval = False\n            \n            bits = line.split(None, 1)\n            if len(bits) == 1:\n                \n                k = bits[0]\n                v = boolval\n            else:\n                \n                k, v = bits\n            ret[k.lower()] = v\n    return ret\n\n\nif __name__ == '__main__':\n    import sys\n    conf = readconf(sys.argv[1])\n    for k, v in sorted(conf.items()):\n        print k, '=', v\n"}
{"id": 40838, "name": "Read a configuration file", "Go": "package config\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"strings\"\n\t\"io/ioutil\"\n)\n\nvar (\n\tENONE    = errors.New(\"Requested value does not exist\")\n\tEBADTYPE = errors.New(\"Requested type and actual type do not match\")\n\tEBADVAL  = errors.New(\"Value and type do not match\")\n)\n\ntype varError struct {\n\terr error\n\tn   string\n\tt   VarType\n}\n\nfunc (err *varError) Error() string {\n\treturn fmt.Sprintf(\"%v: (%q, %v)\", err.err, err.n, err.t)\n}\n\ntype VarType int\n\nconst (\n\tBool VarType = 1 + iota\n\tArray\n\tString\n)\n\nfunc (t VarType) String() string {\n\tswitch t {\n\tcase Bool:\n\t\treturn \"Bool\"\n\tcase Array:\n\t\treturn \"Array\"\n\tcase String:\n\t\treturn \"String\"\n\t}\n\n\tpanic(\"Unknown VarType\")\n}\n\ntype confvar struct {\n\tType VarType\n\tVal  interface{}\n}\n\ntype Config struct {\n\tm map[string]confvar\n}\n\nfunc Parse(r io.Reader) (c *Config, err error) {\n\tc = new(Config)\n\tc.m = make(map[string]confvar)\n\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlines := bytes.Split(buf, []byte{'\\n'})\n\n\tfor _, line := range lines {\n\t\tline = bytes.TrimSpace(line)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch line[0] {\n\t\tcase '#', ';':\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := bytes.SplitN(line, []byte{' '}, 2)\n\t\tnam := string(bytes.ToLower(parts[0]))\n\n\t\tif len(parts) == 1 {\n\t\t\tc.m[nam] = confvar{Bool, true}\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(string(parts[1]), \",\") {\n\t\t\ttmpB := bytes.Split(parts[1], []byte{','})\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpB[i] = bytes.TrimSpace(tmpB[i])\n\t\t\t}\n\t\t\ttmpS := make([]string, 0, len(tmpB))\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpS = append(tmpS, string(tmpB[i]))\n\t\t\t}\n\n\t\t\tc.m[nam] = confvar{Array, tmpS}\n\t\t\tcontinue\n\t\t}\n\n\t\tc.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))}\n\t}\n\n\treturn\n}\n\nfunc (c *Config) Bool(name string) (bool, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn false, nil\n\t}\n\n\tif c.m[name].Type != Bool {\n\t\treturn false, &varError{EBADTYPE, name, Bool}\n\t}\n\n\tv, ok := c.m[name].Val.(bool)\n\tif !ok {\n\t\treturn false, &varError{EBADVAL, name, Bool}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) Array(name string) ([]string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn nil, &varError{ENONE, name, Array}\n\t}\n\n\tif c.m[name].Type != Array {\n\t\treturn nil, &varError{EBADTYPE, name, Array}\n\t}\n\n\tv, ok := c.m[name].Val.([]string)\n\tif !ok {\n\t\treturn nil, &varError{EBADVAL, name, Array}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) String(name string) (string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn \"\", &varError{ENONE, name, String}\n\t}\n\n\tif c.m[name].Type != String {\n\t\treturn \"\", &varError{EBADTYPE, name, String}\n\t}\n\n\tv, ok := c.m[name].Val.(string)\n\tif !ok {\n\t\treturn \"\", &varError{EBADVAL, name, String}\n\t}\n\n\treturn v, nil\n}\n", "Python": "def readconf(fn):\n    ret = {}\n    with file(fn) as fp:\n        for line in fp:\n            \n            line = line.strip()\n            if not line or line.startswith('\n            \n            boolval = True\n            \n            if line.startswith(';'):\n                \n                line = line.lstrip(';')\n                \n                if len(line.split()) != 1: continue\n                boolval = False\n            \n            bits = line.split(None, 1)\n            if len(bits) == 1:\n                \n                k = bits[0]\n                v = boolval\n            else:\n                \n                k, v = bits\n            ret[k.lower()] = v\n    return ret\n\n\nif __name__ == '__main__':\n    import sys\n    conf = readconf(sys.argv[1])\n    for k, v in sorted(conf.items()):\n        print k, '=', v\n"}
{"id": 40839, "name": "Sort using a custom comparator", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\ntype sortable []string\n\nfunc (s sortable) Len() int      { return len(s) }\nfunc (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s sortable) Less(i, j int) bool {\n    a, b := s[i], s[j]\n    if len(a) != len(b) {\n        return len(a) > len(b)\n    }\n    return strings.ToLower(a) < strings.ToLower(b)\n}\n\nfunc main() {\n    var s sortable = strings.Fields(\"To tell your name the livelong day To an admiring bog\")\n    fmt.Println(s, \"(original)\")\n\n    sort.Sort(s)\n    fmt.Println(s, \"(sorted)\")\n}\n", "Python": "strings = \"here are Some sample strings to be sorted\".split()\n\ndef mykey(x):\n    return -len(x), x.upper()\n\nprint sorted(strings, key=mykey)\n"}
{"id": 40840, "name": "Circular primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"strings\"\n)\n\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc repunit(n int) *big.Int {\n    ones := strings.Repeat(\"1\", n)\n    b, _ := new(big.Int).SetString(ones, 10)\n    return b\n}\n\nvar circs = []int{}\n\n\nfunc alreadyFound(n int) bool {\n    for _, i := range circs {\n        if i == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc isCircular(n int) bool {\n    nn := n\n    pow := 1 \n    for nn > 0 {\n        pow *= 10\n        nn /= 10\n    }\n    nn = n\n    for {\n        nn *= 10\n        f := nn / pow \n        nn += f * (1 - pow)\n        if alreadyFound(nn) {\n            return false\n        }\n        if nn == n {\n            break\n        }\n        if !isPrime(nn) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"The first 19 circular primes are:\")\n    digits := [4]int{1, 3, 7, 9}\n    q := []int{1, 2, 3, 5, 7, 9}  \n    fq := []int{1, 2, 3, 5, 7, 9} \n    count := 0\n    for {\n        f := q[0]   \n        fd := fq[0] \n        if isPrime(f) && isCircular(f) {\n            circs = append(circs, f)\n            count++\n            if count == 19 {\n                break\n            }\n        }\n        copy(q, q[1:])   \n        q = q[:len(q)-1] \n        copy(fq, fq[1:]) \n        fq = fq[:len(fq)-1]\n        if f == 2 || f == 5 { \n            continue\n        }\n        \n        \n        for _, d := range digits {\n            if d >= fd {\n                q = append(q, f*10+d)\n                fq = append(fq, fd)\n            }\n        }\n    }\n    fmt.Println(circs)\n    fmt.Println(\"\\nThe next 4 circular primes, in repunit format, are:\")\n    count = 0\n    var rus []string\n    for i := 7; count < 4; i++ {\n        if repunit(i).ProbablyPrime(10) {\n            count++\n            rus = append(rus, fmt.Sprintf(\"R(%d)\", i))\n        }\n    }\n    fmt.Println(rus)\n    fmt.Println(\"\\nThe following repunits are probably circular primes:\")\n    for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} {\n        fmt.Printf(\"R(%-5d) : %t\\n\", i, repunit(i).ProbablyPrime(10))\n    }\n}\n", "Python": "import random\n\ndef is_Prime(n):\n    \n    if n!=int(n):\n        return False\n    n=int(n)\n    \n    if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:\n        return False\n\n    if n==2 or n==3 or n==5 or n==7:\n        return True\n    s = 0\n    d = n-1\n    while d%2==0:\n        d>>=1\n        s+=1\n    assert(2**s * d == n-1)\n\n    def trial_composite(a):\n        if pow(a, d, n) == 1:\n            return False\n        for i in range(s):\n            if pow(a, 2**i * d, n) == n-1:\n                return False\n        return True\n\n    for i in range(8):\n        a = random.randrange(2, n)\n        if trial_composite(a):\n            return False\n\n    return True\n\ndef isPrime(n: int) -> bool:\n    \n    \n    if (n <= 1) :\n        return False\n    if (n <= 3) :\n        return True\n    \n    \n    if (n % 2 == 0 or n % 3 == 0) :\n        return False\n    i = 5\n    while(i * i <= n) :\n        if (n % i == 0 or n % (i + 2) == 0) :\n            return False\n        i = i + 6\n    return True\n\ndef rotations(n: int)-> set((int,)):\n    \n    a = str(n)\n    return set(int(a[i:] + a[:i]) for i in range(len(a)))\n\ndef isCircular(n: int) -> bool:\n    \n    return all(isPrime(int(o)) for o in rotations(n))\n\nfrom itertools import product\n\ndef main():\n    result = [2, 3, 5, 7]\n    first = '137'\n    latter = '1379'\n    for i in range(1, 6):\n        s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))\n        while s:\n            a = s.pop()\n            b = rotations(a)\n            if isCircular(a):\n                result.append(min(b))\n            s -= b\n    result.sort()\n    return result\n\nassert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()\n\n\nrepunit = lambda n: int('1' * n)\n\ndef repmain(n: int) -> list:\n    \n    result = []\n    i = 2\n    while len(result) < n:\n        if is_Prime(repunit(i)):\n            result.append(i)\n        i += 1\n    return result\n\nassert [2, 19, 23, 317, 1031] == repmain(5)\n\n\n"}
{"id": 40841, "name": "Animation", "Go": "package main\n\nimport (\n    \"log\"\n    \"time\"\n\n    \"github.com/gdamore/tcell\"\n)\n\nconst (\n    msg             = \"Hello World! \"\n    x0, y0          = 8, 3\n    shiftsPerSecond = 4\n    clicksToExit    = 5\n)\n\nfunc main() {\n    s, err := tcell.NewScreen()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = s.Init(); err != nil {\n        log.Fatal(err)\n    }\n    s.Clear()\n    s.EnableMouse()\n    tick := time.Tick(time.Second / shiftsPerSecond)\n    click := make(chan bool)\n    go func() {\n        for {\n            em, ok := s.PollEvent().(*tcell.EventMouse)\n            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {\n                continue\n            }\n            mx, my := em.Position()\n            if my == y0 && mx >= x0 && mx < x0+len(msg) {\n                click <- true\n            }\n        }\n    }()\n    for inc, shift, clicks := 1, 0, 0; ; {\n        select {\n        case <-tick:\n            shift = (shift + inc) % len(msg)\n            for i, r := range msg {\n                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)\n            }\n            s.Show()\n        case <-click:\n            clicks++\n            if clicks == clicksToExit {\n                s.Fini()\n                return\n            }\n            inc = len(msg) - inc\n        }\n    }\n}\n", "Python": "txt = \"Hello, world! \"\nleft = True\n\ndef draw():\n    global txt\n    background(128)\n    text(txt, 10, height / 2)\n    if frameCount % 10 == 0:\n        if (left):\n            txt = rotate(txt, 1)\n        else:\n            txt = rotate(txt, -1)\n        println(txt)\n\ndef mouseReleased():\n    global left\n    left = not left\n\ndef rotate(text, startIdx):\n    rotated = text[startIdx:] + text[:startIdx]\n    return rotated\n"}
{"id": 40842, "name": "Animation", "Go": "package main\n\nimport (\n    \"log\"\n    \"time\"\n\n    \"github.com/gdamore/tcell\"\n)\n\nconst (\n    msg             = \"Hello World! \"\n    x0, y0          = 8, 3\n    shiftsPerSecond = 4\n    clicksToExit    = 5\n)\n\nfunc main() {\n    s, err := tcell.NewScreen()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = s.Init(); err != nil {\n        log.Fatal(err)\n    }\n    s.Clear()\n    s.EnableMouse()\n    tick := time.Tick(time.Second / shiftsPerSecond)\n    click := make(chan bool)\n    go func() {\n        for {\n            em, ok := s.PollEvent().(*tcell.EventMouse)\n            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {\n                continue\n            }\n            mx, my := em.Position()\n            if my == y0 && mx >= x0 && mx < x0+len(msg) {\n                click <- true\n            }\n        }\n    }()\n    for inc, shift, clicks := 1, 0, 0; ; {\n        select {\n        case <-tick:\n            shift = (shift + inc) % len(msg)\n            for i, r := range msg {\n                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)\n            }\n            s.Show()\n        case <-click:\n            clicks++\n            if clicks == clicksToExit {\n                s.Fini()\n                return\n            }\n            inc = len(msg) - inc\n        }\n    }\n}\n", "Python": "txt = \"Hello, world! \"\nleft = True\n\ndef draw():\n    global txt\n    background(128)\n    text(txt, 10, height / 2)\n    if frameCount % 10 == 0:\n        if (left):\n            txt = rotate(txt, 1)\n        else:\n            txt = rotate(txt, -1)\n        println(txt)\n\ndef mouseReleased():\n    global left\n    left = not left\n\ndef rotate(text, startIdx):\n    rotated = text[startIdx:] + text[:startIdx]\n    return rotated\n"}
{"id": 40843, "name": "Sorting algorithms_Radix sort", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/binary\"\n    \"fmt\"\n)\n\n\ntype word int32\nconst wordLen = 4\nconst highBit = -1 << 31\n\nvar data = []word{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    buf := bytes.NewBuffer(nil)\n    ds := make([][]byte, len(data))\n    for i, x := range data {\n        binary.Write(buf, binary.LittleEndian, x^highBit)\n        b := make([]byte, wordLen)\n        buf.Read(b)\n        ds[i] = b\n    }\n    bins := make([][][]byte, 256)\n    for i := 0; i < wordLen; i++ {\n        for _, b := range ds {\n            bins[b[i]] = append(bins[b[i]], b)\n        }\n        j := 0\n        for k, bs := range bins {\n            copy(ds[j:], bs)\n            j += len(bs)\n            bins[k] = bs[:0]\n        }\n    }\n    fmt.Println(\"original:\", data)\n    var w word\n    for i, b := range ds {\n        buf.Write(b)\n        binary.Read(buf, binary.LittleEndian, &w)\n        data[i] = w^highBit\n    }\n    fmt.Println(\"sorted:  \", data)\n}\n", "Python": "\nfrom math import log\n \ndef getDigit(num, base, digit_num):\n    \n    return (num // base ** digit_num) % base  \n \ndef makeBlanks(size):\n    \n    return [ [] for i in range(size) ]  \n \ndef split(a_list, base, digit_num):\n    buckets = makeBlanks(base)\n    for num in a_list:\n        \n        buckets[getDigit(num, base, digit_num)].append(num)  \n    return buckets\n \n\ndef merge(a_list):\n    new_list = []\n    for sublist in a_list:\n       new_list.extend(sublist)\n    return new_list\n \ndef maxAbs(a_list):\n    \n    return max(abs(num) for num in a_list)\n\ndef split_by_sign(a_list):\n    \n    \n    buckets = [[], []]\n    for num in a_list:\n        if num < 0:\n            buckets[0].append(num)\n        else:\n            buckets[1].append(num)\n    return buckets\n \ndef radixSort(a_list, base):\n    \n    passes = int(round(log(maxAbs(a_list), base)) + 1) \n    new_list = list(a_list)\n    for digit_num in range(passes):\n        new_list = merge(split(new_list, base, digit_num))\n    return merge(split_by_sign(new_list))\n"}
{"id": 40844, "name": "List comprehensions", "Go": "package main\n\nimport \"fmt\"\n\ntype (\n    seq  []int\n    sofs []seq\n)\n\nfunc newSeq(start, end int) seq {\n    if end < start {\n        end = start\n    }\n    s := make(seq, end-start+1)\n    for i := 0; i < len(s); i++ {\n        s[i] = start + i\n    }\n    return s\n}\n\nfunc newSofs() sofs {\n    return sofs{seq{}}\n}\n\nfunc (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {\n    var s2 sofs\n    for _, t := range expr(s, in) {\n        if pred(t) {\n            s2 = append(s2, t)\n        }\n    }\n    return s2\n}\n\nfunc (s sofs) build(t seq) sofs {\n    var u sofs\n    for _, ss := range s {\n        for _, tt := range t {\n            uu := make(seq, len(ss))\n            copy(uu, ss)\n            uu = append(uu, tt)\n            u = append(u, uu)\n        }\n    }\n    return u\n}\n\nfunc main() {\n    pt := newSofs()\n    in := newSeq(1, 20)\n    expr := func(s sofs, t seq) sofs {\n        return s.build(t).build(t).build(t)\n    }\n    pred := func(t seq) bool {\n        if len(t) != 3 {\n            return false\n        }\n        return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]\n    }\n    pt = pt.listComp(in, expr, pred)\n    fmt.Println(pt)\n}\n", "Python": "[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]\n"}
{"id": 40845, "name": "Sorting algorithms_Selection sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    selectionSort(a)\n    fmt.Println(\"after: \", a)\n}\n\nfunc selectionSort(a []int) {\n    last := len(a) - 1\n    for i := 0; i < last; i++ {\n        aMin := a[i]\n        iMin := i\n        for j := i + 1; j < len(a); j++ {\n            if a[j] < aMin {\n                aMin = a[j]\n                iMin = j\n            }\n        }\n        a[i], a[iMin] = aMin, a[i]\n    }\n}\n", "Python": "def selection_sort(lst):\n    for i, e in enumerate(lst):\n        mn = min(range(i,len(lst)), key=lst.__getitem__)\n        lst[i], lst[mn] = lst[mn], e\n    return lst\n"}
{"id": 40846, "name": "Jacobi symbol", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n)\n\nfunc jacobi(a, n uint64) int {\n    if n%2 == 0 {\n        log.Fatal(\"'n' must be a positive odd integer\")\n    }\n    a %= n\n    result := 1\n    for a != 0 {\n        for a%2 == 0 {\n            a /= 2\n            nn := n % 8\n            if nn == 3 || nn == 5 {\n                result = -result\n            }\n        }\n        a, n = n, a\n        if a%4 == 3 && n%4 == 3 {\n            result = -result\n        }\n        a %= n\n    }\n    if n == 1 {\n        return result\n    }\n    return 0\n}\n\nfunc main() {\n    fmt.Println(\"Using hand-coded version:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            fmt.Printf(\" % d\", jacobi(a, n))\n        }\n        fmt.Println()\n    }\n\n    ba, bn := new(big.Int), new(big.Int)\n    fmt.Println(\"\\nUsing standard library function:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            ba.SetUint64(a)\n            bn.SetUint64(n)\n            fmt.Printf(\" % d\", big.Jacobi(ba, bn))            \n        }\n        fmt.Println()\n    }\n}\n", "Python": "def jacobi(a, n):\n    if n <= 0:\n        raise ValueError(\"'n' must be a positive integer.\")\n    if n % 2 == 0:\n        raise ValueError(\"'n' must be odd.\")\n    a %= n\n    result = 1\n    while a != 0:\n        while a % 2 == 0:\n            a /= 2\n            n_mod_8 = n % 8\n            if n_mod_8 in (3, 5):\n                result = -result\n        a, n = n, a\n        if a % 4 == 3 and n % 4 == 3:\n            result = -result\n        a %= n\n    if n == 1:\n        return result\n    else:\n        return 0\n"}
{"id": 40847, "name": "Jacobi symbol", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n)\n\nfunc jacobi(a, n uint64) int {\n    if n%2 == 0 {\n        log.Fatal(\"'n' must be a positive odd integer\")\n    }\n    a %= n\n    result := 1\n    for a != 0 {\n        for a%2 == 0 {\n            a /= 2\n            nn := n % 8\n            if nn == 3 || nn == 5 {\n                result = -result\n            }\n        }\n        a, n = n, a\n        if a%4 == 3 && n%4 == 3 {\n            result = -result\n        }\n        a %= n\n    }\n    if n == 1 {\n        return result\n    }\n    return 0\n}\n\nfunc main() {\n    fmt.Println(\"Using hand-coded version:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            fmt.Printf(\" % d\", jacobi(a, n))\n        }\n        fmt.Println()\n    }\n\n    ba, bn := new(big.Int), new(big.Int)\n    fmt.Println(\"\\nUsing standard library function:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            ba.SetUint64(a)\n            bn.SetUint64(n)\n            fmt.Printf(\" % d\", big.Jacobi(ba, bn))            \n        }\n        fmt.Println()\n    }\n}\n", "Python": "def jacobi(a, n):\n    if n <= 0:\n        raise ValueError(\"'n' must be a positive integer.\")\n    if n % 2 == 0:\n        raise ValueError(\"'n' must be odd.\")\n    a %= n\n    result = 1\n    while a != 0:\n        while a % 2 == 0:\n            a /= 2\n            n_mod_8 = n % 8\n            if n_mod_8 in (3, 5):\n                result = -result\n        a, n = n, a\n        if a % 4 == 3 and n % 4 == 3:\n            result = -result\n        a %= n\n    if n == 1:\n        return result\n    else:\n        return 0\n"}
{"id": 40848, "name": "K-d tree", "Go": "\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\n\ntype point []float64\n\n\nfunc (p point) sqd(q point) float64 {\n    var sum float64\n    for dim, pCoord := range p {\n        d := pCoord - q[dim]\n        sum += d * d\n    }\n    return sum\n}\n\n\n\n\ntype kdNode struct {\n    domElt      point\n    split       int\n    left, right *kdNode\n}   \n\ntype kdTree struct {\n    n      *kdNode\n    bounds hyperRect\n}\n    \ntype hyperRect struct {\n    min, max point\n}\n\n\n\nfunc (hr hyperRect) copy() hyperRect {\n    return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}\n}   \n    \n\n\n\nfunc newKd(pts []point, bounds hyperRect) kdTree {\n    var nk2 func([]point, int) *kdNode\n    nk2 = func(exset []point, split int) *kdNode {\n        if len(exset) == 0 {\n            return nil\n        }\n        \n        \n        \n        sort.Sort(part{exset, split})\n        m := len(exset) / 2\n        d := exset[m]\n        for m+1 < len(exset) && exset[m+1][split] == d[split] {\n            m++\n        }\n        \n        s2 := split + 1\n        if s2 == len(d) {\n            s2 = 0\n        }\n        return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}\n    }\n    return kdTree{nk2(pts, 0), bounds}\n}\n\n\n\ntype part struct {\n    pts   []point\n    dPart int\n}\n\n\nfunc (p part) Len() int { return len(p.pts) }\nfunc (p part) Less(i, j int) bool {\n    return p.pts[i][p.dPart] < p.pts[j][p.dPart]\n}\nfunc (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }\n\n\n\n\n\nfunc (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {\n    return nn(t.n, p, t.bounds, math.Inf(1))\n}\n\n\n\nfunc nn(kd *kdNode, target point, hr hyperRect,\n    maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {\n    if kd == nil {\n        return nil, math.Inf(1), 0\n    }\n    nodesVisited++\n    s := kd.split\n    pivot := kd.domElt\n    leftHr := hr.copy()\n    rightHr := hr.copy()\n    leftHr.max[s] = pivot[s]\n    rightHr.min[s] = pivot[s]\n    targetInLeft := target[s] <= pivot[s]\n    var nearerKd, furtherKd *kdNode\n    var nearerHr, furtherHr hyperRect\n    if targetInLeft {\n        nearerKd, nearerHr = kd.left, leftHr\n        furtherKd, furtherHr = kd.right, rightHr\n    } else {\n        nearerKd, nearerHr = kd.right, rightHr\n        furtherKd, furtherHr = kd.left, leftHr\n    }\n    var nv int\n    nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)\n    nodesVisited += nv\n    if distSqd < maxDistSqd {\n        maxDistSqd = distSqd\n    }\n    d := pivot[s] - target[s]\n    d *= d\n    if d > maxDistSqd {\n        return\n    }\n    if d = pivot.sqd(target); d < distSqd {\n        nearest = pivot\n        distSqd = d\n        maxDistSqd = distSqd\n    }\n    tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)\n    nodesVisited += nv\n    if tempSqd < distSqd {\n        nearest = tempNearest\n        distSqd = tempSqd\n    }\n    return\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},\n        hyperRect{point{0, 0}, point{10, 10}})\n    showNearest(\"WP example data\", kd, point{9, 2})\n    kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})\n    showNearest(\"1000 random 3d points\", kd, randomPt(3))\n}   \n    \nfunc randomPt(dim int) point {\n    p := make(point, dim)\n    for d := range p {\n        p[d] = rand.Float64()\n    }\n    return p\n}   \n    \nfunc randomPts(dim, n int) []point {\n    p := make([]point, n)\n    for i := range p {\n        p[i] = randomPt(dim) \n    } \n    return p\n}\n    \nfunc showNearest(heading string, kd kdTree, p point) {\n    fmt.Println()\n    fmt.Println(heading)\n    fmt.Println(\"point:           \", p)\n    nn, ssq, nv := kd.nearest(p)\n    fmt.Println(\"nearest neighbor:\", nn)\n    fmt.Println(\"distance:        \", math.Sqrt(ssq))\n    fmt.Println(\"nodes visited:   \", nv)\n}\n", "Python": "from random import seed, random\nfrom time import time\nfrom operator import itemgetter\nfrom collections import namedtuple\nfrom math import sqrt\nfrom copy import deepcopy\n\n\ndef sqd(p1, p2):\n    return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))\n\n\nclass KdNode(object):\n    __slots__ = (\"dom_elt\", \"split\", \"left\", \"right\")\n\n    def __init__(self, dom_elt, split, left, right):\n        self.dom_elt = dom_elt\n        self.split = split\n        self.left = left\n        self.right = right\n\n\nclass Orthotope(object):\n    __slots__ = (\"min\", \"max\")\n\n    def __init__(self, mi, ma):\n        self.min, self.max = mi, ma\n\n\nclass KdTree(object):\n    __slots__ = (\"n\", \"bounds\")\n\n    def __init__(self, pts, bounds):\n        def nk2(split, exset):\n            if not exset:\n                return None\n            exset.sort(key=itemgetter(split))\n            m = len(exset) // 2\n            d = exset[m]\n            while m + 1 < len(exset) and exset[m + 1][split] == d[split]:\n                m += 1\n            d = exset[m]\n\n\n            s2 = (split + 1) % len(d)  \n            return KdNode(d, split, nk2(s2, exset[:m]),\n                                    nk2(s2, exset[m + 1:]))\n        self.n = nk2(0, pts)\n        self.bounds = bounds\n\nT3 = namedtuple(\"T3\", \"nearest dist_sqd nodes_visited\")\n\n\ndef find_nearest(k, t, p):\n    def nn(kd, target, hr, max_dist_sqd):\n        if kd is None:\n            return T3([0.0] * k, float(\"inf\"), 0)\n\n        nodes_visited = 1\n        s = kd.split\n        pivot = kd.dom_elt\n        left_hr = deepcopy(hr)\n        right_hr = deepcopy(hr)\n        left_hr.max[s] = pivot[s]\n        right_hr.min[s] = pivot[s]\n\n        if target[s] <= pivot[s]:\n            nearer_kd, nearer_hr = kd.left, left_hr\n            further_kd, further_hr = kd.right, right_hr\n        else:\n            nearer_kd, nearer_hr = kd.right, right_hr\n            further_kd, further_hr = kd.left, left_hr\n\n        n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)\n        nearest = n1.nearest\n        dist_sqd = n1.dist_sqd\n        nodes_visited += n1.nodes_visited\n\n        if dist_sqd < max_dist_sqd:\n            max_dist_sqd = dist_sqd\n        d = (pivot[s] - target[s]) ** 2\n        if d > max_dist_sqd:\n            return T3(nearest, dist_sqd, nodes_visited)\n        d = sqd(pivot, target)\n        if d < dist_sqd:\n            nearest = pivot\n            dist_sqd = d\n            max_dist_sqd = dist_sqd\n\n        n2 = nn(further_kd, target, further_hr, max_dist_sqd)\n        nodes_visited += n2.nodes_visited\n        if n2.dist_sqd < dist_sqd:\n            nearest = n2.nearest\n            dist_sqd = n2.dist_sqd\n\n        return T3(nearest, dist_sqd, nodes_visited)\n\n    return nn(t.n, p, t.bounds, float(\"inf\"))\n\n\ndef show_nearest(k, heading, kd, p):\n    print(heading + \":\")\n    print(\"Point:           \", p)\n    n = find_nearest(k, kd, p)\n    print(\"Nearest neighbor:\", n.nearest)\n    print(\"Distance:        \", sqrt(n.dist_sqd))\n    print(\"Nodes visited:   \", n.nodes_visited, \"\\n\")\n\n\ndef random_point(k):\n    return [random() for _ in range(k)]\n\n\ndef random_points(k, n):\n    return [random_point(k) for _ in range(n)]\n\nif __name__ == \"__main__\":\n    seed(1)\n    P = lambda *coords: list(coords)\n    kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],\n                  Orthotope(P(0, 0), P(10, 10)))\n    show_nearest(2, \"Wikipedia example data\", kd1, P(9, 2))\n\n    N = 400000\n    t0 = time()\n    kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))\n    t1 = time()\n    text = lambda *parts: \"\".join(map(str, parts))\n    show_nearest(2, text(\"k-d tree with \", N,\n                         \" random 3D points (generation time: \",\n                         t1-t0, \"s)\"),\n                 kd2, random_point(3))\n"}
{"id": 40849, "name": "K-d tree", "Go": "\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\n\ntype point []float64\n\n\nfunc (p point) sqd(q point) float64 {\n    var sum float64\n    for dim, pCoord := range p {\n        d := pCoord - q[dim]\n        sum += d * d\n    }\n    return sum\n}\n\n\n\n\ntype kdNode struct {\n    domElt      point\n    split       int\n    left, right *kdNode\n}   \n\ntype kdTree struct {\n    n      *kdNode\n    bounds hyperRect\n}\n    \ntype hyperRect struct {\n    min, max point\n}\n\n\n\nfunc (hr hyperRect) copy() hyperRect {\n    return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}\n}   \n    \n\n\n\nfunc newKd(pts []point, bounds hyperRect) kdTree {\n    var nk2 func([]point, int) *kdNode\n    nk2 = func(exset []point, split int) *kdNode {\n        if len(exset) == 0 {\n            return nil\n        }\n        \n        \n        \n        sort.Sort(part{exset, split})\n        m := len(exset) / 2\n        d := exset[m]\n        for m+1 < len(exset) && exset[m+1][split] == d[split] {\n            m++\n        }\n        \n        s2 := split + 1\n        if s2 == len(d) {\n            s2 = 0\n        }\n        return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}\n    }\n    return kdTree{nk2(pts, 0), bounds}\n}\n\n\n\ntype part struct {\n    pts   []point\n    dPart int\n}\n\n\nfunc (p part) Len() int { return len(p.pts) }\nfunc (p part) Less(i, j int) bool {\n    return p.pts[i][p.dPart] < p.pts[j][p.dPart]\n}\nfunc (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }\n\n\n\n\n\nfunc (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {\n    return nn(t.n, p, t.bounds, math.Inf(1))\n}\n\n\n\nfunc nn(kd *kdNode, target point, hr hyperRect,\n    maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {\n    if kd == nil {\n        return nil, math.Inf(1), 0\n    }\n    nodesVisited++\n    s := kd.split\n    pivot := kd.domElt\n    leftHr := hr.copy()\n    rightHr := hr.copy()\n    leftHr.max[s] = pivot[s]\n    rightHr.min[s] = pivot[s]\n    targetInLeft := target[s] <= pivot[s]\n    var nearerKd, furtherKd *kdNode\n    var nearerHr, furtherHr hyperRect\n    if targetInLeft {\n        nearerKd, nearerHr = kd.left, leftHr\n        furtherKd, furtherHr = kd.right, rightHr\n    } else {\n        nearerKd, nearerHr = kd.right, rightHr\n        furtherKd, furtherHr = kd.left, leftHr\n    }\n    var nv int\n    nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)\n    nodesVisited += nv\n    if distSqd < maxDistSqd {\n        maxDistSqd = distSqd\n    }\n    d := pivot[s] - target[s]\n    d *= d\n    if d > maxDistSqd {\n        return\n    }\n    if d = pivot.sqd(target); d < distSqd {\n        nearest = pivot\n        distSqd = d\n        maxDistSqd = distSqd\n    }\n    tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)\n    nodesVisited += nv\n    if tempSqd < distSqd {\n        nearest = tempNearest\n        distSqd = tempSqd\n    }\n    return\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},\n        hyperRect{point{0, 0}, point{10, 10}})\n    showNearest(\"WP example data\", kd, point{9, 2})\n    kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})\n    showNearest(\"1000 random 3d points\", kd, randomPt(3))\n}   \n    \nfunc randomPt(dim int) point {\n    p := make(point, dim)\n    for d := range p {\n        p[d] = rand.Float64()\n    }\n    return p\n}   \n    \nfunc randomPts(dim, n int) []point {\n    p := make([]point, n)\n    for i := range p {\n        p[i] = randomPt(dim) \n    } \n    return p\n}\n    \nfunc showNearest(heading string, kd kdTree, p point) {\n    fmt.Println()\n    fmt.Println(heading)\n    fmt.Println(\"point:           \", p)\n    nn, ssq, nv := kd.nearest(p)\n    fmt.Println(\"nearest neighbor:\", nn)\n    fmt.Println(\"distance:        \", math.Sqrt(ssq))\n    fmt.Println(\"nodes visited:   \", nv)\n}\n", "Python": "from random import seed, random\nfrom time import time\nfrom operator import itemgetter\nfrom collections import namedtuple\nfrom math import sqrt\nfrom copy import deepcopy\n\n\ndef sqd(p1, p2):\n    return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))\n\n\nclass KdNode(object):\n    __slots__ = (\"dom_elt\", \"split\", \"left\", \"right\")\n\n    def __init__(self, dom_elt, split, left, right):\n        self.dom_elt = dom_elt\n        self.split = split\n        self.left = left\n        self.right = right\n\n\nclass Orthotope(object):\n    __slots__ = (\"min\", \"max\")\n\n    def __init__(self, mi, ma):\n        self.min, self.max = mi, ma\n\n\nclass KdTree(object):\n    __slots__ = (\"n\", \"bounds\")\n\n    def __init__(self, pts, bounds):\n        def nk2(split, exset):\n            if not exset:\n                return None\n            exset.sort(key=itemgetter(split))\n            m = len(exset) // 2\n            d = exset[m]\n            while m + 1 < len(exset) and exset[m + 1][split] == d[split]:\n                m += 1\n            d = exset[m]\n\n\n            s2 = (split + 1) % len(d)  \n            return KdNode(d, split, nk2(s2, exset[:m]),\n                                    nk2(s2, exset[m + 1:]))\n        self.n = nk2(0, pts)\n        self.bounds = bounds\n\nT3 = namedtuple(\"T3\", \"nearest dist_sqd nodes_visited\")\n\n\ndef find_nearest(k, t, p):\n    def nn(kd, target, hr, max_dist_sqd):\n        if kd is None:\n            return T3([0.0] * k, float(\"inf\"), 0)\n\n        nodes_visited = 1\n        s = kd.split\n        pivot = kd.dom_elt\n        left_hr = deepcopy(hr)\n        right_hr = deepcopy(hr)\n        left_hr.max[s] = pivot[s]\n        right_hr.min[s] = pivot[s]\n\n        if target[s] <= pivot[s]:\n            nearer_kd, nearer_hr = kd.left, left_hr\n            further_kd, further_hr = kd.right, right_hr\n        else:\n            nearer_kd, nearer_hr = kd.right, right_hr\n            further_kd, further_hr = kd.left, left_hr\n\n        n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)\n        nearest = n1.nearest\n        dist_sqd = n1.dist_sqd\n        nodes_visited += n1.nodes_visited\n\n        if dist_sqd < max_dist_sqd:\n            max_dist_sqd = dist_sqd\n        d = (pivot[s] - target[s]) ** 2\n        if d > max_dist_sqd:\n            return T3(nearest, dist_sqd, nodes_visited)\n        d = sqd(pivot, target)\n        if d < dist_sqd:\n            nearest = pivot\n            dist_sqd = d\n            max_dist_sqd = dist_sqd\n\n        n2 = nn(further_kd, target, further_hr, max_dist_sqd)\n        nodes_visited += n2.nodes_visited\n        if n2.dist_sqd < dist_sqd:\n            nearest = n2.nearest\n            dist_sqd = n2.dist_sqd\n\n        return T3(nearest, dist_sqd, nodes_visited)\n\n    return nn(t.n, p, t.bounds, float(\"inf\"))\n\n\ndef show_nearest(k, heading, kd, p):\n    print(heading + \":\")\n    print(\"Point:           \", p)\n    n = find_nearest(k, kd, p)\n    print(\"Nearest neighbor:\", n.nearest)\n    print(\"Distance:        \", sqrt(n.dist_sqd))\n    print(\"Nodes visited:   \", n.nodes_visited, \"\\n\")\n\n\ndef random_point(k):\n    return [random() for _ in range(k)]\n\n\ndef random_points(k, n):\n    return [random_point(k) for _ in range(n)]\n\nif __name__ == \"__main__\":\n    seed(1)\n    P = lambda *coords: list(coords)\n    kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],\n                  Orthotope(P(0, 0), P(10, 10)))\n    show_nearest(2, \"Wikipedia example data\", kd1, P(9, 2))\n\n    N = 400000\n    t0 = time()\n    kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))\n    t1 = time()\n    text = lambda *parts: \"\".join(map(str, parts))\n    show_nearest(2, text(\"k-d tree with \", N,\n                         \" random 3D points (generation time: \",\n                         t1-t0, \"s)\"),\n                 kd2, random_point(3))\n"}
{"id": 40850, "name": "Apply a callback to an array", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, i := range []int{1, 2, 3, 4, 5} {\n        fmt.Println(i * i)\n    }\n}\n", "Python": "def square(n):\n    return n * n\n  \nnumbers = [1, 3, 5, 7]\n\nsquares1 = [square(n) for n in numbers]     \n\nsquares2a = map(square, numbers)            \n\nsquares2b = map(lambda x: x*x, numbers)     \n\nsquares3 = [n * n for n in numbers]         \n                                            \n\nisquares1 = (n * n for n in numbers)        \n\nimport itertools\nisquares2 = itertools.imap(square, numbers) \n"}
{"id": 40851, "name": "Apply a callback to an array", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, i := range []int{1, 2, 3, 4, 5} {\n        fmt.Println(i * i)\n    }\n}\n", "Python": "def square(n):\n    return n * n\n  \nnumbers = [1, 3, 5, 7]\n\nsquares1 = [square(n) for n in numbers]     \n\nsquares2a = map(square, numbers)            \n\nsquares2b = map(lambda x: x*x, numbers)     \n\nsquares3 = [n * n for n in numbers]         \n                                            \n\nisquares1 = (n * n for n in numbers)        \n\nimport itertools\nisquares2 = itertools.imap(square, numbers) \n"}
{"id": 40852, "name": "Singleton", "Go": "package main\n\nimport (\n    \"log\"\n    \"math/rand\"\n    \"sync\"\n    \"time\"\n)\n\nvar (\n    instance string\n    once     sync.Once \n)\n\nfunc claim(color string, w *sync.WaitGroup) {\n    time.Sleep(time.Duration(rand.Intn(1e8))) \n    log.Println(\"trying to claim\", color)\n    once.Do(func() { instance = color })\n    log.Printf(\"tried %s. instance: %s\", color, instance)\n    w.Done()\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    var w sync.WaitGroup\n    w.Add(2)\n    go claim(\"red\", &w) \n    go claim(\"blue\", &w)\n    w.Wait()\n    log.Println(\"after trying both, instance =\", instance)\n}\n", "Python": ">>> class Borg(object):\n\t__state = {}\n\tdef __init__(self):\n\t\tself.__dict__ = self.__state\n\t\n\n\t\n>>> b1 = Borg()\n>>> b2 = Borg()\n>>> b1 is b2\nFalse\n>>> b1.datum = range(5)\n>>> b1.datum\n[0, 1, 2, 3, 4]\n>>> b2.datum\n[0, 1, 2, 3, 4]\n>>> b1.datum is b2.datum\nTrue\n>>> \n"}
{"id": 40853, "name": "Safe addition", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype interval struct {\n    lower, upper float64\n}\n\n\nfunc stepAway(x float64) interval {\n    return interval {\n        math.Nextafter(x, math.Inf(-1)),\n        math.Nextafter(x, math.Inf(1))}\n}\n\n\nfunc safeAdd(a, b float64) interval {\n    return stepAway(a + b)\n    \n}\n\n\nfunc main() {\n    a, b := 1.2, .03\n    fmt.Println(a, b, safeAdd(a, b))\n}\n", "Python": ">>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])\n0.9999999999999999\n>>> from math import fsum\n>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])\n1.0\n"}
{"id": 40854, "name": "Case-sensitivity of identifiers", "Go": "package dogs\n\nimport \"fmt\"\n\n\n\nvar dog = \"Salt\"\nvar Dog = \"Pepper\"\nvar DOG = \"Mustard\"\n\nfunc PackageSees() map[*string]int {\n    \n    fmt.Println(\"Package sees:\", dog, Dog, DOG)\n    \n    \n    \n    \n    return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}\n}\n", "Python": ">>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'\n>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)\nThe three dogs are named  Benjamin ,  Samba , and  Bernie\n>>>\n"}
{"id": 40855, "name": "Case-sensitivity of identifiers", "Go": "package dogs\n\nimport \"fmt\"\n\n\n\nvar dog = \"Salt\"\nvar Dog = \"Pepper\"\nvar DOG = \"Mustard\"\n\nfunc PackageSees() map[*string]int {\n    \n    fmt.Println(\"Package sees:\", dog, Dog, DOG)\n    \n    \n    \n    \n    return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}\n}\n", "Python": ">>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'\n>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)\nThe three dogs are named  Benjamin ,  Samba , and  Bernie\n>>>\n"}
{"id": 40856, "name": "Loops_Downward for", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n", "Python": "for i in xrange(10, -1, -1):\n    print i\n"}
{"id": 40857, "name": "Write entire file", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n"}
{"id": 40858, "name": "Loops_For", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 5; i++ {\n        for j := 1; j <= i; j++ {\n            fmt.Printf(\"*\")\n        }\n        fmt.Printf(\"\\n\")\n    }\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 40859, "name": "Loops_For", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 5; i++ {\n        for j := 1; j <= i; j++ {\n            fmt.Printf(\"*\")\n        }\n        fmt.Printf(\"\\n\")\n    }\n}\n", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n"}
{"id": 40860, "name": "Palindromic gapful numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(s uint64) uint64 {\n    e := uint64(0)\n    for s > 0 {\n        e = e*10 + (s % 10)\n        s /= 10\n    }\n    return e\n}\n\nfunc commatize(n uint) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc ord(n uint) string {\n    var suffix string\n    if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {\n        suffix = \"th\"\n    } else {\n        switch n % 10 {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        default:\n            suffix = \"th\"\n        }\n    }\n    return fmt.Sprintf(\"%s%s\", commatize(n), suffix)\n}\n\nfunc main() {\n    const max = 10_000_000\n    data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},\n        {1e6, 1e6, 16}, {1e7, 1e7, 18}}\n    results := make(map[uint][]uint64)\n    for _, d := range data {\n        for i := d[0]; i <= d[1]; i++ {\n            results[i] = make([]uint64, 9)\n        }\n    }\n    var p uint64\nouter:\n    for d := uint64(1); d < 10; d++ {\n        count := uint(0)\n        pow := uint64(1)\n        fl := d * 11\n        for nd := 3; nd < 20; nd++ {\n            slim := (d + 1) * pow\n            for s := d * pow; s < slim; s++ {\n                e := reverse(s)\n                mlim := uint64(1)\n                if nd%2 == 1 {\n                    mlim = 10\n                }\n                for m := uint64(0); m < mlim; m++ {\n                    if nd%2 == 0 {\n                        p = s*pow*10 + e\n                    } else {\n                        p = s*pow*100 + m*pow*10 + e\n                    }\n                    if p%fl == 0 {\n                        count++\n                        if _, ok := results[count]; ok {\n                            results[count][d-1] = p\n                        }\n                        if count == max {\n                            continue outer\n                        }\n                    }\n                }\n            }\n            if nd%2 == 1 {\n                pow *= 10\n            }\n        }\n    }\n\n    for _, d := range data {\n        if d[0] != d[1] {\n            fmt.Printf(\"%s to %s palindromic gapful numbers (> 100) ending with:\\n\", ord(d[0]), ord(d[1]))\n        } else {\n            fmt.Printf(\"%s palindromic gapful number (> 100) ending with:\\n\", ord(d[0]))\n        }\n        for i := 1; i <= 9; i++ {\n            fmt.Printf(\"%d: \", i)\n            for j := d[0]; j <= d[1]; j++ {\n                fmt.Printf(\"%*d \", d[2], results[j][i-1])\n            }\n            fmt.Println()\n        }\n        fmt.Println()\n    }\n}\n", "Python": "from itertools import count\nfrom pprint import pformat\nimport re\nimport heapq\n\n\ndef pal_part_gen(odd=True):\n    for i in count(1):\n        fwd = str(i)\n        rev = fwd[::-1][1:] if odd else fwd[::-1]\n        yield int(fwd + rev)\n\ndef pal_ordered_gen():\n    yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))\n\ndef is_gapful(x):\n    return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)\n\nif __name__ == '__main__':\n    start = 100\n    for mx, last in [(20, 20), (100, 15), (1_000, 10)]:\n        print(f\"\\nLast {last} of the first {mx} binned-by-last digit \" \n              f\"gapful numbers >= {start}\")\n        bin = {i: [] for i in range(1, 10)}\n        gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))\n        while any(len(val) < mx for val in bin.values()):\n            g = next(gen)\n            val = bin[g % 10]\n            if len(val) < mx:\n                val.append(g)\n        b = {k:v[-last:] for k, v in bin.items()}\n        txt = pformat(b, width=220)\n        print('', re.sub(r\"[{},\\[\\]]\", '', txt))\n"}
{"id": 40861, "name": "Palindromic gapful numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(s uint64) uint64 {\n    e := uint64(0)\n    for s > 0 {\n        e = e*10 + (s % 10)\n        s /= 10\n    }\n    return e\n}\n\nfunc commatize(n uint) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc ord(n uint) string {\n    var suffix string\n    if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {\n        suffix = \"th\"\n    } else {\n        switch n % 10 {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        default:\n            suffix = \"th\"\n        }\n    }\n    return fmt.Sprintf(\"%s%s\", commatize(n), suffix)\n}\n\nfunc main() {\n    const max = 10_000_000\n    data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},\n        {1e6, 1e6, 16}, {1e7, 1e7, 18}}\n    results := make(map[uint][]uint64)\n    for _, d := range data {\n        for i := d[0]; i <= d[1]; i++ {\n            results[i] = make([]uint64, 9)\n        }\n    }\n    var p uint64\nouter:\n    for d := uint64(1); d < 10; d++ {\n        count := uint(0)\n        pow := uint64(1)\n        fl := d * 11\n        for nd := 3; nd < 20; nd++ {\n            slim := (d + 1) * pow\n            for s := d * pow; s < slim; s++ {\n                e := reverse(s)\n                mlim := uint64(1)\n                if nd%2 == 1 {\n                    mlim = 10\n                }\n                for m := uint64(0); m < mlim; m++ {\n                    if nd%2 == 0 {\n                        p = s*pow*10 + e\n                    } else {\n                        p = s*pow*100 + m*pow*10 + e\n                    }\n                    if p%fl == 0 {\n                        count++\n                        if _, ok := results[count]; ok {\n                            results[count][d-1] = p\n                        }\n                        if count == max {\n                            continue outer\n                        }\n                    }\n                }\n            }\n            if nd%2 == 1 {\n                pow *= 10\n            }\n        }\n    }\n\n    for _, d := range data {\n        if d[0] != d[1] {\n            fmt.Printf(\"%s to %s palindromic gapful numbers (> 100) ending with:\\n\", ord(d[0]), ord(d[1]))\n        } else {\n            fmt.Printf(\"%s palindromic gapful number (> 100) ending with:\\n\", ord(d[0]))\n        }\n        for i := 1; i <= 9; i++ {\n            fmt.Printf(\"%d: \", i)\n            for j := d[0]; j <= d[1]; j++ {\n                fmt.Printf(\"%*d \", d[2], results[j][i-1])\n            }\n            fmt.Println()\n        }\n        fmt.Println()\n    }\n}\n", "Python": "from itertools import count\nfrom pprint import pformat\nimport re\nimport heapq\n\n\ndef pal_part_gen(odd=True):\n    for i in count(1):\n        fwd = str(i)\n        rev = fwd[::-1][1:] if odd else fwd[::-1]\n        yield int(fwd + rev)\n\ndef pal_ordered_gen():\n    yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))\n\ndef is_gapful(x):\n    return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)\n\nif __name__ == '__main__':\n    start = 100\n    for mx, last in [(20, 20), (100, 15), (1_000, 10)]:\n        print(f\"\\nLast {last} of the first {mx} binned-by-last digit \" \n              f\"gapful numbers >= {start}\")\n        bin = {i: [] for i in range(1, 10)}\n        gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))\n        while any(len(val) < mx for val in bin.values()):\n            g = next(gen)\n            val = bin[g % 10]\n            if len(val) < mx:\n                val.append(g)\n        b = {k:v[-last:] for k, v in bin.items()}\n        txt = pformat(b, width=220)\n        print('', re.sub(r\"[{},\\[\\]]\", '', txt))\n"}
{"id": 40862, "name": "Sierpinski triangle_Graphical", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"os\"\n)\n\nfunc main() {\n    const order = 8\n    const width = 1 << order\n    const margin = 10\n    bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)\n    im := image.NewGray(bounds)\n    gBlack := color.Gray{0}\n    gWhite := color.Gray{255}\n    draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)\n\n    for y := 0; y < width; y++ {\n        for x := 0; x < width; x++ {\n            if x&y == 0 {\n                im.SetGray(x, y, gBlack)\n            }\n        }\n    }\n    f, err := os.Create(\"sierpinski.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, im); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "\nimport turtle as t\ndef sier(n,length):\n    if n == 0:\n        return\n    for i in range(3):\n        sier(n - 1, length / 2)\n        t.fd(length)\n        t.rt(120)\n"}
{"id": 40863, "name": "Sierpinski triangle_Graphical", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"os\"\n)\n\nfunc main() {\n    const order = 8\n    const width = 1 << order\n    const margin = 10\n    bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)\n    im := image.NewGray(bounds)\n    gBlack := color.Gray{0}\n    gWhite := color.Gray{255}\n    draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)\n\n    for y := 0; y < width; y++ {\n        for x := 0; x < width; x++ {\n            if x&y == 0 {\n                im.SetGray(x, y, gBlack)\n            }\n        }\n    }\n    f, err := os.Create(\"sierpinski.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, im); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "\nimport turtle as t\ndef sier(n,length):\n    if n == 0:\n        return\n    for i in range(3):\n        sier(n - 1, length / 2)\n        t.fd(length)\n        t.rt(120)\n"}
{"id": 40864, "name": "Summarize primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum, n, c := 0, 0, 0\n    fmt.Println(\"Summing the first n primes (<1,000) where the sum is itself prime:\")\n    fmt.Println(\"  n  cumulative sum\")\n    for _, p := range primes {\n        n++\n        sum += p\n        if rcu.IsPrime(sum) {\n            c++\n            fmt.Printf(\"%3d   %6s\\n\", n, rcu.Commatize(sum))\n        }\n    }\n    fmt.Println()\n    fmt.Println(c, \"such prime sums found\")\n}\n", "Python": "\n\n\nfrom itertools import accumulate, chain, takewhile\n\n\n\ndef primeSums():\n    \n    return (\n        x for x in enumerate(\n            accumulate(\n                chain([(0, 0)], primes()),\n                lambda a, p: (p, p + a[1])\n            )\n        ) if isPrime(x[1][1])\n    )\n\n\n\n\ndef main():\n    \n    for x in takewhile(\n            lambda t: 1000 > t[1][0],\n            primeSums()\n    ):\n        print(f'{x[0]} -> {x[1][1]}')\n\n\n\n\n\ndef isPrime(n):\n    \n    if n in (2, 3):\n        return True\n    if 2 > n or 0 == n % 2:\n        return False\n    if 9 > n:\n        return True\n    if 0 == n % 3:\n        return False\n\n    def p(x):\n        return 0 == n % x or 0 == n % (2 + x)\n\n    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))\n\n\n\ndef primes():\n    \n    n = 2\n    dct = {}\n    while True:\n        if n in dct:\n            for p in dct[n]:\n                dct.setdefault(n + p, []).append(p)\n            del dct[n]\n        else:\n            yield n\n            dct[n * n] = [n]\n        n = 1 + n\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40865, "name": "Summarize primes", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum, n, c := 0, 0, 0\n    fmt.Println(\"Summing the first n primes (<1,000) where the sum is itself prime:\")\n    fmt.Println(\"  n  cumulative sum\")\n    for _, p := range primes {\n        n++\n        sum += p\n        if rcu.IsPrime(sum) {\n            c++\n            fmt.Printf(\"%3d   %6s\\n\", n, rcu.Commatize(sum))\n        }\n    }\n    fmt.Println()\n    fmt.Println(c, \"such prime sums found\")\n}\n", "Python": "\n\n\nfrom itertools import accumulate, chain, takewhile\n\n\n\ndef primeSums():\n    \n    return (\n        x for x in enumerate(\n            accumulate(\n                chain([(0, 0)], primes()),\n                lambda a, p: (p, p + a[1])\n            )\n        ) if isPrime(x[1][1])\n    )\n\n\n\n\ndef main():\n    \n    for x in takewhile(\n            lambda t: 1000 > t[1][0],\n            primeSums()\n    ):\n        print(f'{x[0]} -> {x[1][1]}')\n\n\n\n\n\ndef isPrime(n):\n    \n    if n in (2, 3):\n        return True\n    if 2 > n or 0 == n % 2:\n        return False\n    if 9 > n:\n        return True\n    if 0 == n % 3:\n        return False\n\n    def p(x):\n        return 0 == n % x or 0 == n % (2 + x)\n\n    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))\n\n\n\ndef primes():\n    \n    n = 2\n    dct = {}\n    while True:\n        if n in dct:\n            for p in dct[n]:\n                dct.setdefault(n + p, []).append(p)\n            del dct[n]\n        else:\n            yield n\n            dct[n * n] = [n]\n        n = 1 + n\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40866, "name": "Common sorted list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc distinctSortedUnion(ll [][]int) []int {\n    var res []int\n    for _, l := range ll {\n        res = append(res, l...)\n    }\n    set := make(map[int]bool)\n    for _, e := range res {\n        set[e] = true\n    }\n    res = res[:0]\n    for key := range set {\n        res = append(res, key)\n    }\n    sort.Ints(res)\n    return res\n}\n\nfunc main() {\n    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}\n    fmt.Println(\"Distinct sorted union of\", ll, \"is:\")\n    fmt.Println(distinctSortedUnion(ll))\n}\n", "Python": "\n\nfrom itertools import chain\n\n\n\n\ndef main():\n    \n\n    print(\n        sorted(nub(concat([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ])))\n    )\n\n\n\n\n\n\ndef concat(xs):\n    \n    return list(chain(*xs))\n\n\n\ndef nub(xs):\n    \n    return list(dict.fromkeys(xs))\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40867, "name": "Common sorted list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc distinctSortedUnion(ll [][]int) []int {\n    var res []int\n    for _, l := range ll {\n        res = append(res, l...)\n    }\n    set := make(map[int]bool)\n    for _, e := range res {\n        set[e] = true\n    }\n    res = res[:0]\n    for key := range set {\n        res = append(res, key)\n    }\n    sort.Ints(res)\n    return res\n}\n\nfunc main() {\n    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}\n    fmt.Println(\"Distinct sorted union of\", ll, \"is:\")\n    fmt.Println(distinctSortedUnion(ll))\n}\n", "Python": "\n\nfrom itertools import chain\n\n\n\n\ndef main():\n    \n\n    print(\n        sorted(nub(concat([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ])))\n    )\n\n\n\n\n\n\ndef concat(xs):\n    \n    return list(chain(*xs))\n\n\n\ndef nub(xs):\n    \n    return list(dict.fromkeys(xs))\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40868, "name": "Common sorted list", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc distinctSortedUnion(ll [][]int) []int {\n    var res []int\n    for _, l := range ll {\n        res = append(res, l...)\n    }\n    set := make(map[int]bool)\n    for _, e := range res {\n        set[e] = true\n    }\n    res = res[:0]\n    for key := range set {\n        res = append(res, key)\n    }\n    sort.Ints(res)\n    return res\n}\n\nfunc main() {\n    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}\n    fmt.Println(\"Distinct sorted union of\", ll, \"is:\")\n    fmt.Println(distinctSortedUnion(ll))\n}\n", "Python": "\n\nfrom itertools import chain\n\n\n\n\ndef main():\n    \n\n    print(\n        sorted(nub(concat([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ])))\n    )\n\n\n\n\n\n\ndef concat(xs):\n    \n    return list(chain(*xs))\n\n\n\ndef nub(xs):\n    \n    return list(dict.fromkeys(xs))\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40869, "name": "Non-continuous subsequences", "Go": "package main\n\nimport \"fmt\"\n\nconst ( \n    m   = iota \n    c          \n    cm         \n    cmc        \n)\n\nfunc ncs(s []int) [][]int {\n    if len(s) < 3 {\n        return nil\n    }\n    return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)\n}\n\nvar skip = []int{m, cm, cm, cmc}\nvar incl = []int{c, c, cmc, cmc}\n\nfunc n2(ss, tail []int, seq int) [][]int {\n    if len(tail) == 0 {\n        if seq != cmc {\n            return nil\n        }\n        return [][]int{ss}\n    }\n    return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),\n        n2(append(ss, tail[0]), tail[1:], incl[seq])...)\n}\n\nfunc main() {\n    ss := ncs([]int{1, 2, 3, 4})\n    fmt.Println(len(ss), \"non-continuous subsequences:\")\n    for _, s := range ss {\n        fmt.Println(\"  \", s)\n    }\n}\n", "Python": "def ncsub(seq, s=0):\n    if seq:\n        x = seq[:1]\n        xs = seq[1:]\n        p2 = s % 2\n        p1 = not p2\n        return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)\n    else:\n        return [[]] if s >= 3 else []\n"}
{"id": 40870, "name": "Non-continuous subsequences", "Go": "package main\n\nimport \"fmt\"\n\nconst ( \n    m   = iota \n    c          \n    cm         \n    cmc        \n)\n\nfunc ncs(s []int) [][]int {\n    if len(s) < 3 {\n        return nil\n    }\n    return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)\n}\n\nvar skip = []int{m, cm, cm, cmc}\nvar incl = []int{c, c, cmc, cmc}\n\nfunc n2(ss, tail []int, seq int) [][]int {\n    if len(tail) == 0 {\n        if seq != cmc {\n            return nil\n        }\n        return [][]int{ss}\n    }\n    return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),\n        n2(append(ss, tail[0]), tail[1:], incl[seq])...)\n}\n\nfunc main() {\n    ss := ncs([]int{1, 2, 3, 4})\n    fmt.Println(len(ss), \"non-continuous subsequences:\")\n    for _, s := range ss {\n        fmt.Println(\"  \", s)\n    }\n}\n", "Python": "def ncsub(seq, s=0):\n    if seq:\n        x = seq[:1]\n        xs = seq[1:]\n        p2 = s % 2\n        p1 = not p2\n        return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)\n    else:\n        return [[]] if s >= 3 else []\n"}
{"id": 40871, "name": "Fibonacci word_fractal", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"strings\"\n)\n\nfunc wordFractal(i int) string {\n    if i < 2 {\n        if i == 1 {\n            return \"1\"\n        }\n        return \"\"\n    }\n    var f1 strings.Builder\n    f1.WriteString(\"1\")\n    var f2 strings.Builder\n    f2.WriteString(\"0\")\n    for j := i - 2; j >= 1; j-- {\n        tmp := f2.String()\n        f2.WriteString(f1.String())\n        f1.Reset()\n        f1.WriteString(tmp)\n    }\n    return f2.String()\n}\n\nfunc draw(dc *gg.Context, x, y, dx, dy float64, wf string) {\n    for i, c := range wf {\n        dc.DrawLine(x, y, x+dx, y+dy)\n        x += dx\n        y += dy\n        if c == '0' {\n            tx := dx\n            dx = dy\n            if i%2 == 0 {\n                dx = -dy\n            }\n            dy = -tx\n            if i%2 == 0 {\n                dy = tx\n            }\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(450, 620)\n    dc.SetRGB(0, 0, 0)\n    dc.Clear()\n    wf := wordFractal(23)\n    draw(dc, 20, 20, 1, 0, wf)\n    dc.SetRGB(0, 1, 0)\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"fib_wordfractal.png\")\n}\n", "Python": "from functools import wraps\nfrom turtle import *\n\ndef memoize(obj):\n    cache = obj.cache = {}\n    @wraps(obj)\n    def memoizer(*args, **kwargs):\n        key = str(args) + str(kwargs)\n        if key not in cache:\n            cache[key] = obj(*args, **kwargs)\n        return cache[key]\n    return memoizer\n\n@memoize\ndef fibonacci_word(n):\n    assert n > 0\n    if n == 1:\n        return \"1\"\n    if n == 2:\n        return \"0\"\n    return fibonacci_word(n - 1) + fibonacci_word(n - 2)\n\ndef draw_fractal(word, step):\n    for i, c in enumerate(word, 1):\n        forward(step)\n        if c == \"0\":\n            if i % 2 == 0:\n                left(90)\n            else:\n                right(90)\n\ndef main():\n    n = 25 \n    step = 1 \n    width = 1050 \n    height = 1050 \n    w = fibonacci_word(n)\n\n    setup(width=width, height=height)\n    speed(0)\n    setheading(90)\n    left(90)\n    penup()\n    forward(500)\n    right(90)\n    backward(500)\n    pendown()\n    tracer(10000)\n    hideturtle()\n\n    draw_fractal(w, step)\n\n    \n    getscreen().getcanvas().postscript(file=\"fibonacci_word_fractal.eps\")\n    exitonclick()\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 40872, "name": "Twin primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit uint64) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := uint64(3) \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc main() {\n    c := sieve(1e10 - 1)\n    limit := 10\n    start := 3\n    twins := 0\n    for i := 1; i < 11; i++ {\n        for i := start; i < limit; i += 2 {\n            if !c[i] && !c[i-2] {\n                twins++\n            }\n        }\n        fmt.Printf(\"Under %14s there are %10s pairs of twin primes.\\n\", commatize(limit), commatize(twins))\n        start = limit + 1\n        limit *= 10\n    }\n}\n", "Python": "primes = [2, 3, 5, 7, 11, 13, 17, 19]\n\n\ndef count_twin_primes(limit: int) -> int:\n    global primes\n    if limit > primes[-1]:\n        ram_limit = primes[-1] + 90000000 - len(primes)\n        reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1\n\n        while reasonable_limit < limit:\n            ram_limit = primes[-1] + 90000000 - len(primes)\n            if ram_limit > primes[-1]:\n                reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)\n            else:\n                reasonable_limit = min(limit, primes[-1] ** 2)\n\n            sieve = list({x for prime in primes for x in\n                          range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})\n            primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]\n\n    count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])\n\n    return count\n\n\ndef test(limit: int):\n    count = count_twin_primes(limit)\n    print(f\"Number of twin prime pairs less than {limit} is {count}\\n\")\n\n\ntest(10)\ntest(100)\ntest(1000)\ntest(10000)\ntest(100000)\ntest(1000000)\ntest(10000000)\ntest(100000000)\n"}
{"id": 40873, "name": "15 puzzle solver", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    Nr = [16]int{3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3}\n    Nc = [16]int{3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2}\n)\n\nvar (\n    n, _n      int\n    N0, N3, N4 [85]int\n    N2         [85]uint64\n)\n\nconst (\n    i = 1\n    g = 8\n    e = 2\n    l = 4\n)\n\nfunc fY() bool {\n    if N2[n] == 0x123456789abcdef0 {\n        return true\n    }\n    if N4[n] <= _n {\n        return fN()\n    }\n    return false\n}\n\nfunc fZ(w int) bool {\n    if w&i > 0 {\n        fI()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    if w&g > 0 {\n        fG()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    if w&e > 0 {\n        fE()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    if w&l > 0 {\n        fL()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    return false\n}\n\nfunc fN() bool {\n    switch N0[n] {\n    case 0:\n        switch N3[n] {\n        case 'l':\n            return fZ(i)\n        case 'u':\n            return fZ(e)\n        default:\n            return fZ(i + e)\n        }\n    case 3:\n        switch N3[n] {\n        case 'r':\n            return fZ(i)\n        case 'u':\n            return fZ(l)\n        default:\n            return fZ(i + l)\n        }\n    case 1, 2:\n        switch N3[n] {\n        case 'l':\n            return fZ(i + l)\n        case 'r':\n            return fZ(i + e)\n        case 'u':\n            return fZ(e + l)\n        default:\n            return fZ(l + e + i)\n        }\n    case 12:\n        switch N3[n] {\n        case 'l':\n            return fZ(g)\n        case 'd':\n            return fZ(e)\n        default:\n            return fZ(e + g)\n        }\n    case 15:\n        switch N3[n] {\n        case 'r':\n            return fZ(g)\n        case 'd':\n            return fZ(l)\n        default:\n            return fZ(g + l)\n        }\n    case 13, 14:\n        switch N3[n] {\n        case 'l':\n            return fZ(g + l)\n        case 'r':\n            return fZ(e + g)\n        case 'd':\n            return fZ(e + l)\n        default:\n            return fZ(g + e + l)\n        }\n    case 4, 8:\n        switch N3[n] {\n        case 'l':\n            return fZ(i + g)\n        case 'u':\n            return fZ(g + e)\n        case 'd':\n            return fZ(i + e)\n        default:\n            return fZ(i + g + e)\n        }\n    case 7, 11:\n        switch N3[n] {\n        case 'd':\n            return fZ(i + l)\n        case 'u':\n            return fZ(g + l)\n        case 'r':\n            return fZ(i + g)\n        default:\n            return fZ(i + g + l)\n        }\n    default:\n        switch N3[n] {\n        case 'd':\n            return fZ(i + e + l)\n        case 'l':\n            return fZ(i + g + l)\n        case 'r':\n            return fZ(i + g + e)\n        case 'u':\n            return fZ(g + e + l)\n        default:\n            return fZ(i + g + e + l)\n        }\n    }\n}\n\nfunc fI() {\n    g := (11 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] + 4\n    N2[n+1] = N2[n] - a + (a << 16)\n    N3[n+1] = 'd'\n    N4[n+1] = N4[n]\n    cond := Nr[a>>uint(g)] <= N0[n]/4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fG() {\n    g := (19 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] - 4\n    N2[n+1] = N2[n] - a + (a >> 16)\n    N3[n+1] = 'u'\n    N4[n+1] = N4[n]\n    cond := Nr[a>>uint(g)] >= N0[n]/4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fE() {\n    g := (14 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] + 1\n    N2[n+1] = N2[n] - a + (a << 4)\n    N3[n+1] = 'r'\n    N4[n+1] = N4[n]\n    cond := Nc[a>>uint(g)] <= N0[n]%4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fL() {\n    g := (16 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] - 1\n    N2[n+1] = N2[n] - a + (a >> 4)\n    N3[n+1] = 'l'\n    N4[n+1] = N4[n]\n    cond := Nc[a>>uint(g)] >= N0[n]%4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fifteenSolver(n int, g uint64) {\n    N0[0] = n\n    N2[0] = g\n    N4[0] = 0\n}\n\nfunc solve() {\n    if fN() {\n        fmt.Print(\"Solution found in \", n, \" moves: \")\n        for g := 1; g <= n; g++ {\n            fmt.Printf(\"%c\", N3[g])\n        }\n        fmt.Println()\n    } else {\n        n = 0\n        _n++\n        solve()\n    }\n}\n\nfunc main() {\n    fifteenSolver(8, 0xfe169b4c0a73d852)\n    solve()\n}\n", "Python": "import random\n\n\nclass IDAStar:\n    def __init__(self, h, neighbours):\n        \n\n        self.h = h\n        self.neighbours = neighbours\n        self.FOUND = object()\n\n\n    def solve(self, root, is_goal, max_cost=None):\n        \n\n        self.is_goal = is_goal\n        self.path = [root]\n        self.is_in_path = {root}\n        self.path_descrs = []\n        self.nodes_evaluated = 0\n\n        bound = self.h(root)\n\n        while True:\n            t = self._search(0, bound)\n            if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated\n            if t is None: return None\n            bound = t\n\n    def _search(self, g, bound):\n        self.nodes_evaluated += 1\n\n        node = self.path[-1]\n        f = g + self.h(node)\n        if f > bound: return f\n        if self.is_goal(node): return self.FOUND\n\n        m = None \n        for cost, n, descr in self.neighbours(node):\n            if n in self.is_in_path: continue\n\n            self.path.append(n)\n            self.is_in_path.add(n)\n            self.path_descrs.append(descr)\n            t = self._search(g + cost, bound)\n\n            if t == self.FOUND: return self.FOUND\n            if m is None or (t is not None and t < m): m = t\n\n            self.path.pop()\n            self.path_descrs.pop()\n            self.is_in_path.remove(n)\n\n        return m\n\n\ndef slide_solved_state(n):\n    return tuple(i % (n*n) for i in range(1, n*n+1))\n\ndef slide_randomize(p, neighbours):\n    for _ in range(len(p) ** 2):\n        _, p, _ = random.choice(list(neighbours(p)))\n    return p\n\ndef slide_neighbours(n):\n    movelist = []\n    for gap in range(n*n):\n        x, y = gap % n, gap // n\n        moves = []\n        if x > 0: moves.append(-1)    \n        if x < n-1: moves.append(+1)  \n        if y > 0: moves.append(-n)    \n        if y < n-1: moves.append(+n)  \n        movelist.append(moves)\n\n    def neighbours(p):\n        gap = p.index(0)\n        l = list(p)\n\n        for m in movelist[gap]:\n            l[gap] = l[gap + m]\n            l[gap + m] = 0\n            yield (1, tuple(l), (l[gap], m))\n            l[gap + m] = l[gap]\n            l[gap] = 0\n\n    return neighbours\n\ndef slide_print(p):\n    n = int(round(len(p) ** 0.5))\n    l = len(str(n*n))\n    for i in range(0, len(p), n):\n        print(\" \".join(\"{:>{}}\".format(x, l) for x in p[i:i+n]))\n\ndef encode_cfg(cfg, n):\n    r = 0\n    b = n.bit_length()\n    for i in range(len(cfg)):\n        r |= cfg[i] << (b*i)\n    return r\n\n\ndef gen_wd_table(n):\n    goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)]\n    goal[-1][-1] = n - 1\n    goal = tuple(sum(goal, []))\n\n    table = {}\n    to_visit = [(goal, 0, n-1)]\n    while to_visit:\n        cfg, cost, e = to_visit.pop(0)\n        enccfg = encode_cfg(cfg, n)\n        if enccfg in table: continue\n        table[enccfg] = cost\n\n        for d in [-1, 1]:\n            if 0 <= e + d < n:\n                for c in range(n):\n                    if cfg[n*(e+d) + c] > 0:\n                        ncfg = list(cfg)\n                        ncfg[n*(e+d) + c] -= 1\n                        ncfg[n*e + c] += 1\n                        to_visit.append((tuple(ncfg), cost + 1, e+d))\n\n    return table\n\ndef slide_wd(n, goal):\n    wd = gen_wd_table(n)\n    goals = {i : goal.index(i) for i in goal}\n    b = n.bit_length()\n\n    def h(p):\n        ht = 0 \n        vt = 0 \n        d = 0\n        for i, c in enumerate(p):\n            if c == 0: continue\n            g = goals[c]\n            xi, yi = i % n, i // n\n            xg, yg = g % n, g // n\n            ht += 1 << (b*(n*yi+yg))\n            vt += 1 << (b*(n*xi+xg))\n\n            if yg == yi:\n                for k in range(i + 1, i - i%n + n): \n                    if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g:\n                        d += 2\n\n            if xg == xi:\n                for k in range(i + n, n * n, n): \n                    if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g:\n                        d += 2\n\n        d += wd[ht] + wd[vt]\n\n        return d\n    return h\n\n\n\n\nif __name__ == \"__main__\":\n    solved_state = slide_solved_state(4)\n    neighbours = slide_neighbours(4)\n    is_goal = lambda p: p == solved_state\n\n    tests = [\n        (15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2),\n    ]\n\n    slide_solver = IDAStar(slide_wd(4, solved_state), neighbours)\n\n    for p in tests:\n        path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80)\n        slide_print(p)\n        print(\", \".join({-1: \"Left\", 1: \"Right\", -4: \"Up\", 4: \"Down\"}[move[1]] for move in moves))\n        print(cost, num_eval)\n"}
{"id": 40874, "name": "Roots of unity", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\nfunc main() {\n    for n := 2; n <= 5; n++ {\n        fmt.Printf(\"%d roots of 1:\\n\", n)\n        for _, r := range roots(n) {\n            fmt.Printf(\"  %18.15f\\n\", r)\n        }\n    }\n}\n\nfunc roots(n int) []complex128 {\n    r := make([]complex128, n)\n    for i := 0; i < n; i++ {\n        r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))\n    }\n    return r\n}\n", "Python": "import cmath\n\n\nclass Complex(complex):\n    def __repr__(self):\n        rp = '%7.5f' % self.real if not self.pureImag() else ''\n        ip = '%7.5fj' % self.imag if not self.pureReal() else ''\n        conj = '' if (\n            self.pureImag() or self.pureReal() or self.imag < 0.0\n        ) else '+'\n        return '0.0' if (\n            self.pureImag() and self.pureReal()\n        ) else rp + conj + ip\n\n    def pureImag(self):\n        return abs(self.real) < 0.000005\n\n    def pureReal(self):\n        return abs(self.imag) < 0.000005\n\n\ndef croots(n):\n    if n <= 0:\n        return None\n    return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))\n    \n    \n\n\nfor nr in range(2, 11):\n    print(nr, list(croots(nr)))\n"}
{"id": 40875, "name": "Long multiplication", "Go": "\n\n\n\n\n\n\n\n\npackage main\n\nimport \"fmt\"\n\n\nfunc d(b byte) byte {\n    if b < '0' || b > '9' {\n        panic(\"digit 0-9 expected\")\n    }\n    return b - '0'\n}\n\n\nfunc add(x, y string) string {\n    if len(y) > len(x) {\n        x, y = y, x\n    }\n    b := make([]byte, len(x)+1)\n    var c byte\n    for i := 1; i <= len(x); i++ {\n        if i <= len(y) {\n            c += d(y[len(y)-i])\n        }\n        s := d(x[len(x)-i]) + c\n        c = s / 10\n        b[len(b)-i] = (s % 10) + '0'\n    }\n    if c == 0 {\n        return string(b[1:])\n    }\n    b[0] = c + '0'\n    return string(b)\n}\n\n\nfunc mulDigit(x string, y byte) string {\n    if y == '0' {\n        return \"0\"\n    }\n    y = d(y)\n    b := make([]byte, len(x)+1)\n    var c byte\n    for i := 1; i <= len(x); i++ {\n        s := d(x[len(x)-i])*y + c\n        c = s / 10\n        b[len(b)-i] = (s % 10) + '0'\n    }\n    if c == 0 {\n        return string(b[1:])\n    }\n    b[0] = c + '0'\n    return string(b)\n}\n\n\nfunc mul(x, y string) string {\n    result := mulDigit(x, y[len(y)-1])\n    for i, zeros := 2, \"\"; i <= len(y); i++ {\n        zeros += \"0\"\n        result = add(result, mulDigit(x, y[len(y)-i])+zeros)\n    }\n    return result\n}\n\n\nconst n = \"18446744073709551616\"\n\nfunc main() {\n    fmt.Println(mul(n, n))\n}\n", "Python": "\nprint 2**64*2**64\n"}
{"id": 40876, "name": "Pell's equation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar big1 = new(big.Int).SetUint64(1)\n\nfunc solvePell(nn uint64) (*big.Int, *big.Int) {\n    n := new(big.Int).SetUint64(nn)\n    x := new(big.Int).Set(n)\n    x.Sqrt(x)\n    y := new(big.Int).Set(x)\n    z := new(big.Int).SetUint64(1)\n    r := new(big.Int).Lsh(x, 1)\n\n    e1 := new(big.Int).SetUint64(1)\n    e2 := new(big.Int)\n    f1 := new(big.Int)\n    f2 := new(big.Int).SetUint64(1)\n\n    t := new(big.Int)\n    u := new(big.Int)\n    a := new(big.Int)\n    b := new(big.Int)\n    for {\n        t.Mul(r, z)\n        y.Sub(t, y)\n        t.Mul(y, y)\n        t.Sub(n, t)\n        z.Quo(t, z)\n        t.Add(x, y)\n        r.Quo(t, z)\n        u.Set(e1)\n        e1.Set(e2)\n        t.Mul(r, e2)\n        e2.Add(t, u)\n        u.Set(f1)\n        f1.Set(f2)\n        t.Mul(r, f2)\n        f2.Add(t, u)\n        t.Mul(x, f2)\n        a.Add(e2, t)\n        b.Set(f2)\n        t.Mul(a, a)\n        u.Mul(n, b)\n        u.Mul(u, b)\n        t.Sub(t, u)\n        if t.Cmp(big1) == 0 {\n            return a, b\n        }\n    }\n}\n\nfunc main() {\n    ns := []uint64{61, 109, 181, 277}\n    for _, n := range ns {\n        x, y := solvePell(n)\n        fmt.Printf(\"x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\\n\", n, x, y)\n    }\n}\n", "Python": "import math\n\ndef solvePell(n):\n    x = int(math.sqrt(n))\n    y, z, r = x, 1, x << 1\n    e1, e2 = 1, 0\n    f1, f2 = 0, 1\n    while True:\n        y = r * z - y\n        z = (n - y * y) // z\n        r = (x + y) // z\n\n        e1, e2 = e2, e1 + e2 * r\n        f1, f2 = f2, f1 + f2 * r\n\n        a, b = f2 * x + e2, f2\n        if a * a - n * b * b == 1:\n            return a, b\n\nfor n in [61, 109, 181, 277]:\n    x, y = solvePell(n)\n    print(\"x^2 - %3d * y^2 = 1 for x = %27d and y = %25d\" % (n, x, y))\n"}
{"id": 40877, "name": "Bulls and cows", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Println(`Cows and Bulls\nGuess four digit number of unique digits in the range 1 to 9.\nA correct digit but not in the correct place is a cow.\nA correct digit in the correct place is a bull.`)\n    \n    pat := make([]byte, 4)\n    rand.Seed(time.Now().Unix())\n    r := rand.Perm(9)\n    for i := range pat {\n        pat[i] = '1' + byte(r[i])\n    }\n\n    \n    valid := []byte(\"123456789\")\nguess:\n    for in := bufio.NewReader(os.Stdin); ; {\n        fmt.Print(\"Guess: \")\n        guess, err := in.ReadString('\\n')\n        if err != nil {\n            fmt.Println(\"\\nSo, bye.\")\n            return\n        }\n        guess = strings.TrimSpace(guess)\n        if len(guess) != 4 {\n            \n            fmt.Println(\"Please guess a four digit number.\")\n            continue\n        }\n        var cows, bulls int\n        for ig, cg := range guess {\n            if strings.IndexRune(guess[:ig], cg) >= 0 {\n                \n                fmt.Printf(\"Repeated digit: %c\\n\", cg)\n                continue guess\n            }\n            switch bytes.IndexByte(pat, byte(cg)) {\n            case -1:\n                if bytes.IndexByte(valid, byte(cg)) == -1 {\n                    \n                    fmt.Printf(\"Invalid digit: %c\\n\", cg)\n                    continue guess\n                }\n            default: \n                cows++\n            case ig:\n                bulls++\n            }\n        }\n        fmt.Printf(\"Cows: %d, bulls: %d\\n\", cows, bulls)\n        if bulls == 4 {\n            fmt.Println(\"You got it.\")\n            return\n        }\n    }\n}\n", "Python": "\n\nimport random\n\ndigits = '123456789'\nsize = 4\nchosen = ''.join(random.sample(digits,size))\n\nprint  % (size, size)\nguesses = 0\nwhile True:\n    guesses += 1\n    while True:\n        \n        guess = raw_input('\\nNext guess [%i]: ' % guesses).strip()\n        if len(guess) == size and \\\n           all(char in digits for char in guess) \\\n           and len(set(guess)) == size:\n            break\n        print \"Problem, try again. You need to enter %i unique digits from 1 to 9\" % size\n    if guess == chosen:\n        print '\\nCongratulations you guessed correctly in',guesses,'attempts'\n        break\n    bulls = cows = 0\n    for i in range(size):\n        if guess[i] == chosen[i]:\n            bulls += 1\n        elif guess[i] in chosen:\n            cows += 1\n    print '  %i Bulls\\n  %i Cows' % (bulls, cows)\n"}
{"id": 40878, "name": "Sorting algorithms_Bubble sort", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    bubblesort(list)\n    fmt.Println(\"sorted!  \", list)\n}\n\nfunc bubblesort(a []int) {\n    for itemCount := len(a) - 1; ; itemCount-- {\n        hasChanged := false\n        for index := 0; index < itemCount; index++ {\n            if a[index] > a[index+1] {\n                a[index], a[index+1] = a[index+1], a[index]\n                hasChanged = true\n            }\n        }\n        if hasChanged == false {\n            break\n        }\n    }\n}\n", "Python": "def bubble_sort(seq):\n    \n    changed = True\n    while changed:\n        changed = False\n        for i in range(len(seq) - 1):\n            if seq[i] > seq[i+1]:\n                seq[i], seq[i+1] = seq[i+1], seq[i]\n                changed = True\n    return seq\n\nif __name__ == \"__main__\":\n   \n\n   from random import shuffle\n\n   testset = [_ for _ in range(100)]\n   testcase = testset.copy() \n   shuffle(testcase)\n   assert testcase != testset  \n   bubble_sort(testcase)\n   assert testcase == testset  \n"}
{"id": 40879, "name": "Product of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc prodDivisors(n int) int {\n    prod := 1\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            prod *= i\n            j := n / i\n            if j != i {\n                prod *= j\n            }\n        }\n        i += k\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The products of positive divisors for the first 50 positive integers are:\")\n    for i := 1; i <= 50; i++ {\n        fmt.Printf(\"%9d  \", prodDivisors(i))\n        if i%5 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "def product_of_divisors(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans = i = j = 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans *= i\n            j = n//i\n            if j != i:\n                ans *= j\n        i += 1\n    return ans\n    \nif __name__ == \"__main__\":\n    print([product_of_divisors(n) for n in range(1,51)])\n"}
{"id": 40880, "name": "Product of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc prodDivisors(n int) int {\n    prod := 1\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            prod *= i\n            j := n / i\n            if j != i {\n                prod *= j\n            }\n        }\n        i += k\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The products of positive divisors for the first 50 positive integers are:\")\n    for i := 1; i <= 50; i++ {\n        fmt.Printf(\"%9d  \", prodDivisors(i))\n        if i%5 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Python": "def product_of_divisors(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans = i = j = 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans *= i\n            j = n//i\n            if j != i:\n                ans *= j\n        i += 1\n    return ans\n    \nif __name__ == \"__main__\":\n    print([product_of_divisors(n) for n in range(1,51)])\n"}
{"id": 40881, "name": "File input_output", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"input.txt\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = ioutil.WriteFile(\"output.txt\", b, 0666); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n"}
{"id": 40882, "name": "Arithmetic_Integer", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a, b int\n    fmt.Print(\"enter two integers: \")\n    fmt.Scanln(&a, &b)\n    fmt.Printf(\"%d + %d = %d\\n\", a, b, a+b)\n    fmt.Printf(\"%d - %d = %d\\n\", a, b, a-b)\n    fmt.Printf(\"%d * %d = %d\\n\", a, b, a*b)\n    fmt.Printf(\"%d / %d = %d\\n\", a, b, a/b)  \n    fmt.Printf(\"%d %% %d = %d\\n\", a, b, a%b) \n    \n}\n", "Python": "x = int(raw_input(\"Number 1: \"))\ny = int(raw_input(\"Number 2: \"))\n\nprint \"Sum: %d\" % (x + y)\nprint \"Difference: %d\" % (x - y)\nprint \"Product: %d\" % (x * y)\nprint \"Quotient: %d\" % (x / y)     \n                                   \nprint \"Remainder: %d\" % (x % y)    \nprint \"Quotient: %d with Remainder: %d\" % divmod(x, y)\nprint \"Power: %d\" % x**y\n\n\nraw_input( )\n"}
{"id": 40883, "name": "Matrix transposition", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"gonum.org/v1/gonum/mat\"\n)\n\nfunc main() {\n    m := mat.NewDense(2, 3, []float64{\n        1, 2, 3,\n        4, 5, 6,\n    })\n    fmt.Println(mat.Formatted(m))\n    fmt.Println()\n    fmt.Println(mat.Formatted(m.T()))\n}\n", "Python": "m=((1,  1,  1,   1),\n   (2,  4,  8,  16),\n   (3,  9, 27,  81),\n   (4, 16, 64, 256),\n   (5, 25,125, 625))\nprint(zip(*m))\n\n\n"}
{"id": 40884, "name": "Man or boy test", "Go": "package main\nimport \"fmt\"\n\nfunc a(k int, x1, x2, x3, x4, x5 func() int) int {\n\tvar b func() int\n\tb = func() int {\n\t\tk--\n\t\treturn a(k, b, x1, x2, x3, x4)\n\t}\n\tif k <= 0 {\n\t\treturn x4() + x5()\n\t}\n\treturn b()\n}\n\nfunc main() {\n\tx := func(i int) func() int { return func() int { return i } }\n\tfmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))\n}\n", "Python": "\nimport sys\nsys.setrecursionlimit(1025)\n\ndef a(in_k, x1, x2, x3, x4, x5):\n    k = [in_k]\n    def b():\n        k[0] -= 1\n        return a(k[0], b, x1, x2, x3, x4)\n    return x4() + x5() if k[0] <= 0 else b()\n\nx = lambda i: lambda: i\nprint(a(10, x(1), x(-1), x(-1), x(1), x(0)))\n"}
{"id": 40885, "name": "Short-circuit evaluation", "Go": "package main\n\nimport \"fmt\"\n\nfunc a(v bool) bool {\n    fmt.Print(\"a\")\n    return v\n}\n\nfunc b(v bool) bool {\n    fmt.Print(\"b\")\n    return v\n}\n\nfunc test(i, j bool) {\n    fmt.Printf(\"Testing a(%t) && b(%t)\\n\", i, j)\n    fmt.Print(\"Trace:  \")\n    fmt.Println(\"\\nResult:\", a(i) && b(j))\n\n    fmt.Printf(\"Testing a(%t) || b(%t)\\n\", i, j)\n    fmt.Print(\"Trace:  \")\n    fmt.Println(\"\\nResult:\", a(i) || b(j))\n\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    test(false, false)\n    test(false, true)\n    test(true, false)\n    test(true, true)\n}\n", "Python": ">>> def a(answer):\n\tprint(\"  \n\treturn answer\n\n>>> def b(answer):\n\tprint(\"  \n\treturn answer\n\n>>> for i in (False, True):\n\tfor j in (False, True):\n\t\tprint (\"\\nCalculating: x = a(i) and b(j)\")\n\t\tx = a(i) and b(j)\n\t\tprint (\"Calculating: y = a(i) or  b(j)\")\n\t\ty = a(i) or  b(j)\n\n\t\t\n\nCalculating: x = a(i) and b(j)\n  \nCalculating: y = a(i) or  b(j)\n  \n  \n\nCalculating: x = a(i) and b(j)\n  \nCalculating: y = a(i) or  b(j)\n  \n  \n\nCalculating: x = a(i) and b(j)\n  \n  \nCalculating: y = a(i) or  b(j)\n  \n\nCalculating: x = a(i) and b(j)\n  \n  \nCalculating: y = a(i) or  b(j)\n  \n"}
{"id": 40886, "name": "Find limit of recursion", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"runtime/debug\"\n)\n\nfunc main() {\n\tstack := flag.Int(\"stack\", 0, \"maximum per goroutine stack size or 0 for the default\")\n\tflag.Parse()\n\tif *stack > 0 {\n\t\tdebug.SetMaxStack(*stack)\n\t}\n\tr(1)\n}\n\nfunc r(l int) {\n\tif l%1000 == 0 {\n\t\tfmt.Println(l)\n\t}\n\tr(l + 1)\n}\n", "Python": "import sys\nprint(sys.getrecursionlimit())\n"}
{"id": 40887, "name": "Bitwise operations", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n"}
{"id": 40888, "name": "Dragon curve", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n"}
{"id": 40889, "name": "Read a file line by line", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n"}
{"id": 40890, "name": "Doubly-linked list_Element insertion", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n"}
{"id": 40891, "name": "Quickselect algorithm", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n"}
{"id": 40892, "name": "Non-decimal radices_Convert", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 40893, "name": "Walk a directory_Recursively", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n"}
{"id": 40894, "name": "CRC-32", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 40895, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 40896, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 40897, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 40898, "name": "Classes", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 40899, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 40900, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 40901, "name": "LZW compression", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n"}
{"id": 40902, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 40903, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 40904, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 40905, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 40906, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 40907, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 40908, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 40909, "name": "Anonymous recursion", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n"}
{"id": 40910, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 40911, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 40912, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 40913, "name": "Longest string challenge", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n"}
{"id": 40914, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 40915, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 40916, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 40917, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 40918, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 40919, "name": "Dining philosophers", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n"}
{"id": 40920, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 40921, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 40922, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40923, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40924, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 40925, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 40926, "name": "Spiral matrix", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n"}
{"id": 40927, "name": "Optional parameters", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n"}
{"id": 40928, "name": "Call a foreign-language function", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n"}
{"id": 40929, "name": "Call a foreign-language function", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n"}
{"id": 40930, "name": "Faulhaber's triangle", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40931, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 40932, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 40933, "name": "Word wheel", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n"}
{"id": 40934, "name": "Array concatenation", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 40935, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 40936, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 40937, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 40938, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 40939, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 40940, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 40941, "name": "Primes - allocate descendants to their ancestors", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n"}
{"id": 40942, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40943, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 40944, "name": "Proper divisors", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n"}
{"id": 40945, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n"}
{"id": 40946, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 40947, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 40948, "name": "Regular expressions", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 40949, "name": "Hash from two arrays", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n"}
{"id": 40950, "name": "Colour pinstripe_Display", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n"}
{"id": 40951, "name": "Colour pinstripe_Display", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n"}
{"id": 40952, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n"}
{"id": 40953, "name": "Animate a pendulum", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n"}
{"id": 40954, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 40955, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 40956, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 40957, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 40958, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "VB": "Option Base {0|1}\n"}
{"id": 40959, "name": "Sierpinski carpet", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 40960, "name": "Sorting algorithms_Bogosort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n"}
{"id": 40961, "name": "Euler method", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n"}
{"id": 40962, "name": "Sequence of non-squares", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 40963, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 40964, "name": "JortSort", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n"}
{"id": 40965, "name": "Leap year", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n"}
{"id": 40966, "name": "Combinations and permutations", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n"}
{"id": 40967, "name": "Sort numbers lexicographically", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n"}
{"id": 40968, "name": "Number names", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n"}
{"id": 40969, "name": "Sorting algorithms_Shell sort", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n"}
{"id": 40970, "name": "Doubly-linked list_Definition", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n"}
{"id": 40971, "name": "Letter frequency", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n"}
{"id": 40972, "name": "Increment a numerical string", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 40973, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 40974, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 40975, "name": "Averages_Arithmetic mean", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n"}
{"id": 40976, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40977, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 40978, "name": "Tokenize a string with escaping", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n"}
{"id": 40979, "name": "Hello world_Text", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n"}
{"id": 40980, "name": "Forward difference", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n"}
{"id": 40981, "name": "Primality by trial division", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n"}
{"id": 40982, "name": "Evaluate binomial coefficients", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 40983, "name": "Collections", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 40984, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n"}
{"id": 40985, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n"}
{"id": 40986, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 40987, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 40988, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 40989, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n"}
{"id": 40990, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 40991, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 40992, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n"}
{"id": 40993, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n"}
{"id": 40994, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 40995, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 40996, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 40997, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 40998, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n"}
{"id": 40999, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 41000, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n"}
{"id": 41001, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 41002, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n"}
{"id": 41003, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n"}
{"id": 41004, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 41005, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 41006, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n"}
{"id": 41007, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 41008, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 41009, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 41010, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n"}
{"id": 41011, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n"}
{"id": 41012, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n"}
{"id": 41013, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 41014, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 41015, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 41016, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n"}
{"id": 41017, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n"}
{"id": 41018, "name": "Hello world_Text", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 41019, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 41020, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 41021, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 41022, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 41023, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 41024, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 41025, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 41026, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 41027, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 41028, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 41029, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 41030, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 41031, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 41032, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 41033, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 41034, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 41035, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 41036, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 41037, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 41038, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 41039, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41040, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41041, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41042, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41043, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41044, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41045, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 41046, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 41047, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 41048, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 41049, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 41050, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 41051, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 41052, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 41053, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 41054, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 41055, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 41056, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 41057, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 41058, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 41059, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 41060, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 41061, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 41062, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 41063, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n"}
{"id": 41064, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n"}
{"id": 41065, "name": "Sorting algorithms_Strand sort", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n"}
{"id": 41066, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 41067, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 41068, "name": "Delegates", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 41069, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 41070, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 41071, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 41072, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 41073, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 41074, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 41075, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 41076, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 41077, "name": "Enforced immutability", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 41078, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n"}
{"id": 41079, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n"}
{"id": 41080, "name": "Sutherland-Hodgman polygon clipping", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n"}
{"id": 41081, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 41082, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 41083, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 41084, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 41085, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 41086, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 41087, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 41088, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 41089, "name": "Knuth's algorithm S", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n"}
{"id": 41090, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41091, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41092, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41093, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41094, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41095, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41096, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 41097, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 41098, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 41099, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 41100, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 41101, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 41102, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 41103, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 41104, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 41105, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 41106, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 41107, "name": "First-class functions", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 41108, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 41109, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 41110, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 41111, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 41112, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 41113, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 41114, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 41115, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 41116, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 41117, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n"}
{"id": 41118, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n"}
{"id": 41119, "name": "Fractal tree", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n"}
{"id": 41120, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 41121, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 41122, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 41123, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 41124, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 41125, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 41126, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 41127, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 41128, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 41129, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint(array[0])\n"}
{"id": 41130, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint(array[0])\n"}
{"id": 41131, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint(array[0])\n"}
{"id": 41132, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 41133, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 41134, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 41135, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 41136, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 41137, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 41138, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 41139, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 41140, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 41141, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 41142, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 41143, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 41144, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 41145, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 41146, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 41147, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 41148, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 41149, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 41150, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 41151, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 41152, "name": "Compare length of two strings", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 41153, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 41154, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 41155, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 41156, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 41157, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 41158, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 41159, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 41160, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 41161, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 41162, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n"}
{"id": 41163, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n"}
{"id": 41164, "name": "Sorting algorithms_Permutation sort", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n"}
{"id": 41165, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 41166, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 41167, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 41168, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 41169, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 41170, "name": "Entropy", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 41171, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 41172, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 41173, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 41174, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 41175, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 41176, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 41177, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 41178, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 41179, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 41180, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 41181, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 41182, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 41183, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 41184, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 41185, "name": "Bitmap_Write a PPM file", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 41186, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 41187, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 41188, "name": "Delete a file", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 41189, "name": "Discordian date", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 41190, "name": "Discordian date", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 41191, "name": "Discordian date", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 41192, "name": "String interpolation (included)", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 41193, "name": "String interpolation (included)", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 41194, "name": "String interpolation (included)", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 41195, "name": "Sorting algorithms_Patience sort", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n"}
{"id": 41196, "name": "Sorting algorithms_Patience sort", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n"}
{"id": 41197, "name": "Sorting algorithms_Patience sort", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n"}
{"id": 41198, "name": "Wireworld", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n"}
{"id": 41199, "name": "Wireworld", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n"}
{"id": 41200, "name": "Wireworld", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n"}
{"id": 41201, "name": "Ray-casting algorithm", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 41202, "name": "Ray-casting algorithm", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 41203, "name": "Ray-casting algorithm", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 41204, "name": "Count occurrences of a substring", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 41205, "name": "Count occurrences of a substring", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 41206, "name": "Count occurrences of a substring", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 41207, "name": "Take notes on the command line", "PHP": "#!/usr/bin/php\n<?php\nif ($argc > 1)\n    file_put_contents(\n        'notes.txt', \n        date('r').\"\\n\\t\".implode(' ', array_slice($argv, 1)).\"\\n\",\n        FILE_APPEND\n    );\nelse\n    @readfile('notes.txt');\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open(\"notes.txt\", \"r\") as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open(\"notes.txt\", \"a\") as f:\n        f.write(datetime.datetime.now().isoformat() + \"\\n\")\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 41208, "name": "Take notes on the command line", "PHP": "#!/usr/bin/php\n<?php\nif ($argc > 1)\n    file_put_contents(\n        'notes.txt', \n        date('r').\"\\n\\t\".implode(' ', array_slice($argv, 1)).\"\\n\",\n        FILE_APPEND\n    );\nelse\n    @readfile('notes.txt');\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open(\"notes.txt\", \"r\") as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open(\"notes.txt\", \"a\") as f:\n        f.write(datetime.datetime.now().isoformat() + \"\\n\")\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 41209, "name": "Bitwise operations", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n"}
{"id": 41210, "name": "Read a file line by line", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n"}
{"id": 41211, "name": "Non-decimal radices_Convert", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 41212, "name": "Walk a directory_Recursively", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n"}
{"id": 41213, "name": "CRC-32", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 41214, "name": "Classes", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 41215, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 41216, "name": "Kaprekar numbers", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 41217, "name": "LZW compression", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n"}
{"id": 41218, "name": "Anonymous recursion", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n"}
{"id": 41219, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 41220, "name": "Substring_Top and tail", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 41221, "name": "Longest string challenge", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n"}
{"id": 41222, "name": "Create a file", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 41223, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 41224, "name": "Abbreviations, easy", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 41225, "name": "Call a foreign-language function", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n"}
{"id": 41226, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 41227, "name": "Command-line arguments", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 41228, "name": "Array concatenation", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 41229, "name": "User input_Text", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 41230, "name": "Knapsack problem_0-1", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 41231, "name": "Proper divisors", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n"}
{"id": 41232, "name": "Regular expressions", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 41233, "name": "Hash from two arrays", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n"}
{"id": 41234, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 41235, "name": "Gray code", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 41236, "name": "Playing cards", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n", "VB": "suite$ = \"CDHS\"                 #Club, Diamond, Heart, Spade\ncard$  = \"A23456789TJQK\"        #Cards Ace to King\ncard   = 0\n\ndim n(55)                       #make ordered deck\nfor i = 1 to 52                 # of 52 cards\n    n[i] = i\nnext i\n\nfor i = 1 to 52 * 3             #shuffle deck 3 times\n    i1    = int(rand * 52) + 1\n    i2    = int(rand * 52) + 1\n    h2    = n[i1]\n    n[i1] = n[i2]\n    n[i2] = h2\nnext i\n\nfor hand = 1 to 4               #4 hands\n    for deal = 1 to 13            #deal each 13 cards\n        card += 1               #next card in deck\n        s = (n[card] mod 4)  + 1    #determine suite\n        c = (n[card] mod 13) + 1    #determine card\n        print mid(card$,c,1);mid(suite$,s,1);\" \";  #show the card\n    next deal\n    print\nnext hand\nend\n\nfunction word$(sr$, wn, delim$)\n    j = wn\n    if j = 0 then j += 1\n    res$ = \"\" : s$ = sr$ : d$ = delim$\n    if d$ = \"\" then d$ = \" \"\n    sd = length(d$) : sl = length(s$)\n    while true\n        n = instr(s$,d$) : j -= 1\n        if j = 0 then\n            if n=0 then res$=s$ else res$=mid(s$,1,n-1)\n            return res$\n        end if\n        if n = 0 then return res$\n        if n = sl - sd then res$ = \"\" : return res$\n        sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2\n    end while\n    return res$\nend function\n"}
{"id": 41237, "name": "Arrays", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n", "VB": "Option Base {0|1}\n"}
{"id": 41238, "name": "Sierpinski carpet", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 41239, "name": "Sorting algorithms_Bogosort", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n"}
{"id": 41240, "name": "Sequence of non-squares", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 41241, "name": "Substring", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 41242, "name": "Leap year", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n"}
{"id": 41243, "name": "Number names", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n"}
{"id": 41244, "name": "Sorting algorithms_Shell sort", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n"}
{"id": 41245, "name": "Letter frequency", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n"}
{"id": 41246, "name": "Increment a numerical string", "PHP": "$s = \"12345\";\n$s++;\n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 41247, "name": "Strip a set of characters from a string", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 41248, "name": "Averages_Arithmetic mean", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n"}
{"id": 41249, "name": "Forward difference", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n"}
{"id": 41250, "name": "Primality by trial division", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n"}
{"id": 41251, "name": "Evaluate binomial coefficients", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 41252, "name": "Collections", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 41253, "name": "Bitwise operations", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 41254, "name": "Dragon curve", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n"}
{"id": 41255, "name": "Read a file line by line", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 41256, "name": "Doubly-linked list_Element insertion", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 41257, "name": "Quickselect algorithm", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 41258, "name": "Non-decimal radices_Convert", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 41259, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 41260, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 41261, "name": "Classes", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 41262, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 41263, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 41264, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 41265, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 41266, "name": "Anonymous recursion", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 41267, "name": "Create a file", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 41268, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n"}
{"id": 41269, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 41270, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 41271, "name": "Spiral matrix", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n"}
{"id": 41272, "name": "Faulhaber's triangle", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n"}
{"id": 41273, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 41274, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 41275, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 41276, "name": "User input_Text", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 41277, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 41278, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 41279, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 41280, "name": "First-class functions", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n"}
{"id": 41281, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 41282, "name": "XML_Output", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n"}
{"id": 41283, "name": "Regular expressions", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 41284, "name": "Guess the number_With feedback (player)", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n"}
{"id": 41285, "name": "Hash from two arrays", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 41286, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 41287, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 41288, "name": "Animate a pendulum", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n"}
{"id": 41289, "name": "Sorting algorithms_Heapsort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n"}
{"id": 41290, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 41291, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 41292, "name": "Sierpinski carpet", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 41293, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 41294, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 41295, "name": "Euler method", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n"}
{"id": 41296, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 41297, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 41298, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 41299, "name": "JortSort", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n"}
{"id": 41300, "name": "Leap year", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 41301, "name": "Sort numbers lexicographically", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n"}
{"id": 41302, "name": "Number names", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 41303, "name": "Compare length of two strings", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 41304, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 41305, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 41306, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 41307, "name": "Averages_Arithmetic mean", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 41308, "name": "Entropy", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n"}
{"id": 41309, "name": "Tokenize a string with escaping", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n"}
{"id": 41310, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 41311, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 41312, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 41313, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 41314, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 41315, "name": "Singly-linked list_Traversal", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n"}
{"id": 41316, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 41317, "name": "Delete a file", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 41318, "name": "Delete a file", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 41319, "name": "Discordian date", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 41320, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 41321, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 41322, "name": "String interpolation (included)", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n"}
{"id": 41323, "name": "Partition function P", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n"}
{"id": 41324, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 41325, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 41326, "name": "Take notes on the command line", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n"}
{"id": 41327, "name": "Take notes on the command line", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n"}
{"id": 41328, "name": "Angles (geometric), normalization and conversion", "C#": "using System;\n\npublic static class Angles\n{\n    public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);\n\n    public static void Print(params double[] angles) {\n        string[] names = { \"Degrees\", \"Gradians\", \"Mils\", \"Radians\" };\n        Func<double, double> rnd = a => Math.Round(a, 4);\n        Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };\n\n        Func<double, double>[,] convert = {\n            { a => a, DegToGrad, DegToMil, DegToRad },\n            { GradToDeg, a => a, GradToMil, GradToRad },\n            { MilToDeg, MilToGrad, a => a, MilToRad },\n            { RadToDeg, RadToGrad, RadToMil, a => a }\n        };\n\n        Console.WriteLine($@\"{\"Angle\",-12}{\"Normalized\",-12}{\"Unit\",-12}{\n            \"Degrees\",-12}{\"Gradians\",-12}{\"Mils\",-12}{\"Radians\",-12}\");\n\n        foreach (double angle in angles) {\n            for (int i = 0; i < 4; i++) {\n                double nAngle = normal[i](angle);\n\n                Console.WriteLine($@\"{\n                    rnd(angle),-12}{\n                    rnd(nAngle),-12}{\n                    names[i],-12}{\n                    rnd(convert[i, 0](nAngle)),-12}{\n                    rnd(convert[i, 1](nAngle)),-12}{\n                    rnd(convert[i, 2](nAngle)),-12}{\n                    rnd(convert[i, 3](nAngle)),-12}\");\n            }\n        }\n    }\n\n    public static double NormalizeDeg(double angle) => Normalize(angle, 360);\n    public static double NormalizeGrad(double angle) => Normalize(angle, 400);\n    public static double NormalizeMil(double angle) => Normalize(angle, 6400);\n    public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);\n\n    private static double Normalize(double angle, double N) {\n        while (angle <= -N) angle += N;\n        while (angle >= N) angle -= N;\n        return angle;\n    }\n\n    public static double DegToGrad(double angle) => angle * 10 / 9;\n    public static double DegToMil(double angle) => angle * 160 / 9;\n    public static double DegToRad(double angle) => angle * Math.PI / 180;\n    \n    public static double GradToDeg(double angle) => angle * 9 / 10;\n    public static double GradToMil(double angle) => angle * 16;\n    public static double GradToRad(double angle) => angle * Math.PI / 200;\n    \n    public static double MilToDeg(double angle) => angle * 9 / 160;\n    public static double MilToGrad(double angle) => angle / 16;\n    public static double MilToRad(double angle) => angle * Math.PI / 3200;\n    \n    public static double RadToDeg(double angle) => angle * 180 / Math.PI;\n    public static double RadToGrad(double angle) => angle * 200 / Math.PI;\n    public static double RadToMil(double angle) => angle * 3200 / Math.PI;\n}\n", "Java": "import java.text.DecimalFormat;\n\n\n\npublic class AnglesNormalizationAndConversion {\n\n    public static void main(String[] args) {\n        DecimalFormat formatAngle = new DecimalFormat(\"######0.000000\");\n        DecimalFormat formatConv = new DecimalFormat(\"###0.0000\");\n        System.out.printf(\"                               degrees    gradiens        mils     radians%n\");\n        for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {\n            for ( String units : new String[] {\"degrees\", \"gradiens\", \"mils\", \"radians\"}) {\n                double d = 0, g = 0, m = 0, r = 0;\n                switch (units) {\n                case \"degrees\":\n                    d = d2d(angle);\n                    g = d2g(d);\n                    m = d2m(d);\n                    r = d2r(d);\n                    break;\n                case \"gradiens\":\n                    g = g2g(angle);\n                    d = g2d(g);\n                    m = g2m(g);\n                    r = g2r(g);\n                    break;\n                case \"mils\":\n                    m = m2m(angle);\n                    d = m2d(m);\n                    g = m2g(m);\n                    r = m2r(m);\n                    break;\n                case \"radians\":\n                    r = r2r(angle);\n                    d = r2d(r);\n                    g = r2g(r);\n                    m = r2m(r);\n                    break;\n                }\n                System.out.printf(\"%15s  %8s = %10s  %10s  %10s  %10s%n\", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));\n            }\n        }\n    }\n\n    private static final double DEGREE = 360D;\n    private static final double GRADIAN = 400D;\n    private static final double MIL = 6400D;\n    private static final double RADIAN = (2 * Math.PI);\n    \n    private static double d2d(double a) {\n        return a % DEGREE;\n    }\n    private static double d2g(double a) {\n        return a * (GRADIAN / DEGREE);\n    }\n    private static double d2m(double a) {\n        return a * (MIL / DEGREE);\n    }\n    private static double d2r(double a) {\n        return a * (RADIAN / 360);\n    }\n\n    private static double g2d(double a) {\n        return a * (DEGREE / GRADIAN);\n    }\n    private static double g2g(double a) {\n        return a % GRADIAN;\n    }\n    private static double g2m(double a) {\n        return a * (MIL / GRADIAN);\n    }\n    private static double g2r(double a) {\n        return a * (RADIAN / GRADIAN);\n    }\n    \n    private static double m2d(double a) {\n        return a * (DEGREE / MIL);\n    }\n    private static double m2g(double a) {\n        return a * (GRADIAN / MIL);\n    }\n    private static double m2m(double a) {\n        return a % MIL;\n    }\n    private static double m2r(double a) {\n        return a * (RADIAN / MIL);\n    }\n    \n    private static double r2d(double a) {\n        return a * (DEGREE / RADIAN);\n    }\n    private static double r2g(double a) {\n        return a * (GRADIAN / RADIAN);\n    }\n    private static double r2m(double a) {\n        return a * (MIL / RADIAN);\n    }\n    private static double r2r(double a) {\n        return a % RADIAN;\n    }\n    \n}\n"}
{"id": 41329, "name": "Find common directory path", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n", "Java": "public class CommonPath {\n\tpublic static String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\tfor(int i = 0; i < paths.length; i++){\n\t\t\tfolders[i] = paths[i].split(\"/\"); \n\t\t}\n\t\tfor(int j = 0; j < folders[0].length; j++){\n\t\t\tString thisFolder = folders[0][j]; \n\t\t\tboolean allMatched = true; \n\t\t\tfor(int i = 1; i < folders.length && allMatched; i++){ \n\t\t\t\tif(folders[i].length < j){ \n\t\t\t\t\tallMatched = false; \n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tallMatched &= folders[i][j].equals(thisFolder); \n\t\t\t}\n\t\t\tif(allMatched){ \n\t\t\t\tcommonPath += thisFolder + \"/\"; \n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn commonPath;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString[] paths = { \"/home/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths));\n\t\t\n\t\tString[] paths2 = { \"/hame/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths2));\n\t}\n}\n"}
{"id": 41330, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n"}
{"id": 41331, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n"}
{"id": 41332, "name": "Memory allocation", "C#": "using System;\nusing System.Runtime.InteropServices;\n\npublic unsafe class Program\n{\n    public static unsafe void HeapMemory()\n    {\n        const int HEAP_ZERO_MEMORY = 0x00000008;\n        const int size = 1000;\n        int ph = GetProcessHeap();\n        void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);\n        if (pointer == null)\n            throw new OutOfMemoryException();\n        Console.WriteLine(HeapSize(ph, 0, pointer));\n        HeapFree(ph, 0, pointer);\n    }\n\n    public static unsafe void StackMemory()\n    {\n        byte* buffer = stackalloc byte[1000];\n        \n    }\n    public static void Main(string[] args)\n    {\n        HeapMemory();\n        StackMemory();\n    }\n    [DllImport(\"kernel32\")]\n    static extern void* HeapAlloc(int hHeap, int flags, int size);\n    [DllImport(\"kernel32\")]\n    static extern bool HeapFree(int hHeap, int flags, void* block);\n    [DllImport(\"kernel32\")]\n    static extern int GetProcessHeap();\n    [DllImport(\"kernel32\")]\n    static extern int HeapSize(int hHeap, int flags, void* block);\n\n}\n", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n"}
{"id": 41333, "name": "Integer sequence", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n"}
{"id": 41334, "name": "Integer sequence", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n"}
{"id": 41335, "name": "DNS query", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n", "Java": "import java.net.InetAddress;\nimport java.net.Inet4Address;\nimport java.net.Inet6Address;\nimport java.net.UnknownHostException;\n\nclass DnsQuery {\n    public static void main(String[] args) {\n        try {\n            InetAddress[] ipAddr = InetAddress.getAllByName(\"www.kame.net\");\n            for(int i=0; i < ipAddr.length ; i++) {\n                if (ipAddr[i] instanceof Inet4Address) {\n                    System.out.println(\"IPv4 : \" + ipAddr[i].getHostAddress());\n                } else if (ipAddr[i] instanceof Inet6Address) {\n                    System.out.println(\"IPv6 : \" + ipAddr[i].getHostAddress());\n                }\n            }\n        } catch (UnknownHostException uhe) {\n            System.err.println(\"unknown host\");\n        }\n    }\n}\n"}
{"id": 41336, "name": "Seven-sided dice from five-sided dice", "C#": "using System;\n\npublic class SevenSidedDice\n{\n    Random random = new Random();\n\t\t\n        static void Main(string[] args)\n\t\t{\n\t\t\tSevenSidedDice sevenDice = new SevenSidedDice();\n\t\t\tConsole.WriteLine(\"Random number from 1 to 7: \"+ sevenDice.seven());\n            Console.Read();\n\t\t}\n\t\t\n\t\tint seven()\n\t\t{\n\t\t\tint v=21;\n\t\t\twhile(v>20)\n\t\t\t\tv=five()+five()*5-6;\n\t\t\treturn 1+v%7;\n\t\t}\n\t\t\n\t\tint five()\n\t\t{\n        return 1 + random.Next(5);\n\t\t}\n}\n", "Java": "import java.util.Random;\npublic class SevenSidedDice \n{\n\tprivate static final Random rnd = new Random();\n\tpublic static void main(String[] args)\n\t{\n\t\tSevenSidedDice now=new SevenSidedDice();\n\t\tSystem.out.println(\"Random number from 1 to 7: \"+now.seven());\n\t}\n\tint seven()\n\t{\n\t\tint v=21;\n\t\twhile(v>20)\n\t\t\tv=five()+five()*5-6;\n\t\treturn 1+v%7;\n\t}\n\tint five()\n\t{\n\t\treturn 1+rnd.nextInt(5);\n\t}\n}\n"}
{"id": 41337, "name": "Magnanimous numbers", "C#": "using System; using static System.Console;\n\nclass Program {\n\n  static bool[] np; \n\n  static void ms(long lmt) { \n    np = new bool[lmt]; np[0] = np[1] = true;\n    for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])\n        for (long k = n * n; k < lmt; k += n) np[k] = true; }\n\n  static bool is_Mag(long n) { long res, rem;\n    for (long p = 10; n >= p; p *= 10) {\n      res = Math.DivRem (n, p, out rem);\n      if (np[res + rem]) return false; } return true; }\n\n  static void Main(string[] args) { ms(100_009); string mn;\n    WriteLine(\"First 45{0}\", mn = \" magnanimous numbers:\");\n    for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {\n      if (c++ < 45 || (c > 240 && c <= 250) || c > 390)\n        Write(c <= 45 ? \"{0,4} \" : \"{0,8:n0} \", l);\n      if (c < 45 && c % 15 == 0) WriteLine();\n      if (c == 240) WriteLine (\"\\n\\n241st through 250th{0}\", mn);\n      if (c == 390) WriteLine (\"\\n\\n391st through 400th{0}\", mn); } }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class MagnanimousNumbers {\n\n    public static void main(String[] args) {\n        runTask(\"Find and display the first 45 magnanimous numbers.\", 1, 45);\n        runTask(\"241st through 250th magnanimous numbers.\", 241, 250);\n        runTask(\"391st through 400th magnanimous numbers.\", 391, 400);\n    }\n    \n    private static void runTask(String message, int startN, int endN) {\n        int count = 0;\n        List<Integer> nums = new ArrayList<>();\n        for ( int n = 0 ; count < endN ; n++ ) {\n            if ( isMagnanimous(n) ) {\n                nums.add(n);\n                count++;\n            }\n        }\n        System.out.printf(\"%s%n\", message);\n        System.out.printf(\"%s%n%n\", nums.subList(startN-1, endN));\n    }\n    \n    private static boolean isMagnanimous(long n) {\n        if ( n >= 0 && n <= 9 ) {\n            return true;\n        }\n        long q = 11;\n        for ( long div = 10 ; q >= 10 ; div *= 10 ) {\n            q = n / div;\n            long r = n % div;\n            if ( ! isPrime(q+r) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n"}
{"id": 41338, "name": "Create a two-dimensional array at runtime", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n", "Java": "import java.util.Scanner;\n\npublic class twoDimArray {\n  public static void main(String[] args) {\n        Scanner in = new Scanner(System.in);\n        \n        int nbr1 = in.nextInt();\n        int nbr2 = in.nextInt();\n        \n        double[][] array = new double[nbr1][nbr2];\n        array[0][0] = 42.0;\n        System.out.println(\"The number at place [0 0] is \" + array[0][0]);\n  }\n}\n"}
{"id": 41339, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 41340, "name": "Dragon curve", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n"}
{"id": 41341, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 41342, "name": "Doubly-linked list_Element insertion", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n"}
{"id": 41343, "name": "Smarandache prime-digital sequence", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n"}
{"id": 41344, "name": "Quickselect algorithm", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n"}
{"id": 41345, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 41346, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 41347, "name": "State name puzzle", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n"}
{"id": 41348, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 41349, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 41350, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 41351, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 41352, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 41353, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 41354, "name": "LZW compression", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n"}
{"id": 41355, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 41356, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 41357, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 41358, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 41359, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 41360, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 41361, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 41362, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 41363, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 41364, "name": "Mertens function", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n"}
{"id": 41365, "name": "Order by pair comparisons", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n"}
{"id": 41366, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 41367, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 41368, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 41369, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 41370, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 41371, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 41372, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 41373, "name": "Legendre prime counting function", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n"}
{"id": 41374, "name": "Use another language to call a function", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n"}
{"id": 41375, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n"}
{"id": 41376, "name": "Universal Turing machine", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 41377, "name": "Universal Turing machine", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 41378, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 41379, "name": "Unprimeable numbers", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n"}
{"id": 41380, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 41381, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 41382, "name": "Chernick's Carmichael numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n"}
{"id": 41383, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 41384, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 41385, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 41386, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41387, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41388, "name": "Sequence of primorial primes", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n"}
{"id": 41389, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 41390, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 41391, "name": "Dining philosophers", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n"}
{"id": 41392, "name": "Dining philosophers", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n"}
{"id": 41393, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 41394, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 41395, "name": "Logistic curve fitting in epidemiology", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n"}
{"id": 41396, "name": "Sorting algorithms_Strand sort", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n"}
{"id": 41397, "name": "Additive primes", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n"}
{"id": 41398, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 41399, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 41400, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 41401, "name": "Delegates", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 41402, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41403, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41404, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 41405, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 41406, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 41407, "name": "Enforced immutability", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n"}
{"id": 41408, "name": "Sutherland-Hodgman polygon clipping", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n"}
{"id": 41409, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 41410, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 41411, "name": "Spiral matrix", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n"}
{"id": 41412, "name": "Optional parameters", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n"}
{"id": 41413, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 41414, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 41415, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 41416, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 41417, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 41418, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 41419, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 41420, "name": "Faulhaber's triangle", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n"}
{"id": 41421, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 41422, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 41423, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 41424, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 41425, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 41426, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 41427, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 41428, "name": "Primes - allocate descendants to their ancestors", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n"}
{"id": 41429, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 41430, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 41431, "name": "First-class functions", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 41432, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 41433, "name": "XML_Output", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n"}
{"id": 41434, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 41435, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 41436, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 41437, "name": "Guess the number_With feedback (player)", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n"}
{"id": 41438, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 41439, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 41440, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 41441, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 41442, "name": "Fractal tree", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n"}
{"id": 41443, "name": "Colour pinstripe_Display", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n"}
{"id": 41444, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 41445, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 41446, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n"}
{"id": 41447, "name": "Animate a pendulum", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n"}
{"id": 41448, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 41449, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 41450, "name": "Create a file on magnetic tape", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n"}
{"id": 41451, "name": "Sorting algorithms_Heapsort", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 41452, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 41453, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 41454, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 41455, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 41456, "name": "Euler method", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 41457, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 41458, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 41459, "name": "JortSort", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n"}
{"id": 41460, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 41461, "name": "Combinations and permutations", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n"}
{"id": 41462, "name": "Sort numbers lexicographically", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n"}
{"id": 41463, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 41464, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 41465, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 41466, "name": "Sorting algorithms_Shell sort", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 41467, "name": "Doubly-linked list_Definition", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n"}
{"id": 41468, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 41469, "name": "Permutation test", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n"}
{"id": 41470, "name": "Möbius function", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n"}
{"id": 41471, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 41472, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 41473, "name": "Sorting algorithms_Permutation sort", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n"}
{"id": 41474, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 41475, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 41476, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 41477, "name": "Entropy", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n"}
{"id": 41478, "name": "Tokenize a string with escaping", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n"}
{"id": 41479, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n"}
{"id": 41480, "name": "Sexy primes", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n"}
{"id": 41481, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 41482, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 41483, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 41484, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 41485, "name": "Singly-linked list_Traversal", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 41486, "name": "Singly-linked list_Traversal", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 41487, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 41488, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 41489, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n"}
{"id": 41490, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 41491, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 41492, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 41493, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 41494, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 41495, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 41496, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 41497, "name": "String interpolation (included)", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 41498, "name": "Sorting algorithms_Patience sort", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n"}
{"id": 41499, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 41500, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 41501, "name": "Tau number", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n"}
{"id": 41502, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 41503, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 41504, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 41505, "name": "Partition function P", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n"}
{"id": 41506, "name": "Ray-casting algorithm", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 41507, "name": "Ray-casting algorithm", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 41508, "name": "Elliptic curve arithmetic", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 41509, "name": "Elliptic curve arithmetic", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 41510, "name": "Count occurrences of a substring", "Java": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) / subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n"}
{"id": 41511, "name": "Numbers with prime digits whose sum is 13", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 41512, "name": "Numbers with prime digits whose sum is 13", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 41513, "name": "String comparison", "Java": "public class Compare\n{\n\t\n    \n    public static void compare (String A, String B)\n    {\n        if (A.equals(B))\n            System.debug(A + ' and  ' + B + ' are lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not lexically equal.');\n\n        if (A.equalsIgnoreCase(B))\n            System.debug(A + ' and  ' + B + ' are case-insensitive lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not case-insensitive lexically equal.');\n \n        if (A.compareTo(B) < 0)\n            System.debug(A + ' is lexically before ' + B);\n        else if (A.compareTo(B) > 0)\n            System.debug(A + ' is lexically after ' + B);\n \n        if (A.compareTo(B) >= 0)\n            System.debug(A + ' is not lexically before ' + B);\n        if (A.compareTo(B) <= 0)\n            System.debug(A + ' is not lexically after ' + B);\n \n        System.debug('The lexical relationship is: ' + A.compareTo(B));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n"}
{"id": 41514, "name": "Take notes on the command line", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 41515, "name": "Thiele's interpolation formula", "Java": "import static java.lang.Math.*;\n\npublic class Test {\n    final static int N = 32;\n    final static int N2 = (N * (N - 1) / 2);\n    final static double STEP = 0.05;\n\n    static double[] xval = new double[N];\n    static double[] t_sin = new double[N];\n    static double[] t_cos = new double[N];\n    static double[] t_tan = new double[N];\n\n    static double[] r_sin = new double[N2];\n    static double[] r_cos = new double[N2];\n    static double[] r_tan = new double[N2];\n\n    static double rho(double[] x, double[] y, double[] r, int i, int n) {\n        if (n < 0)\n            return 0;\n\n        if (n == 0)\n            return y[i];\n\n        int idx = (N - 1 - n) * (N - n) / 2 + i;\n        if (r[idx] != r[idx])\n            r[idx] = (x[i] - x[i + n])\n                    / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n                    + rho(x, y, r, i + 1, n - 2);\n\n        return r[idx];\n    }\n\n    static double thiele(double[] x, double[] y, double[] r, double xin, int n) {\n        if (n > N - 1)\n            return 1;\n        return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n                + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < N; i++) {\n            xval[i] = i * STEP;\n            t_sin[i] = sin(xval[i]);\n            t_cos[i] = cos(xval[i]);\n            t_tan[i] = t_sin[i] / t_cos[i];\n        }\n\n        for (int i = 0; i < N2; i++)\n            r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN;\n\n        System.out.printf(\"%16.14f%n\", 6 * thiele(t_sin, xval, r_sin, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 3 * thiele(t_cos, xval, r_cos, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 4 * thiele(t_tan, xval, r_tan, 1.0, 0));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n"}
{"id": 41516, "name": "Fibonacci word", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 41517, "name": "Fibonacci word", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 41518, "name": "Angles (geometric), normalization and conversion", "Java": "import java.text.DecimalFormat;\n\n\n\npublic class AnglesNormalizationAndConversion {\n\n    public static void main(String[] args) {\n        DecimalFormat formatAngle = new DecimalFormat(\"######0.000000\");\n        DecimalFormat formatConv = new DecimalFormat(\"###0.0000\");\n        System.out.printf(\"                               degrees    gradiens        mils     radians%n\");\n        for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {\n            for ( String units : new String[] {\"degrees\", \"gradiens\", \"mils\", \"radians\"}) {\n                double d = 0, g = 0, m = 0, r = 0;\n                switch (units) {\n                case \"degrees\":\n                    d = d2d(angle);\n                    g = d2g(d);\n                    m = d2m(d);\n                    r = d2r(d);\n                    break;\n                case \"gradiens\":\n                    g = g2g(angle);\n                    d = g2d(g);\n                    m = g2m(g);\n                    r = g2r(g);\n                    break;\n                case \"mils\":\n                    m = m2m(angle);\n                    d = m2d(m);\n                    g = m2g(m);\n                    r = m2r(m);\n                    break;\n                case \"radians\":\n                    r = r2r(angle);\n                    d = r2d(r);\n                    g = r2g(r);\n                    m = r2m(r);\n                    break;\n                }\n                System.out.printf(\"%15s  %8s = %10s  %10s  %10s  %10s%n\", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));\n            }\n        }\n    }\n\n    private static final double DEGREE = 360D;\n    private static final double GRADIAN = 400D;\n    private static final double MIL = 6400D;\n    private static final double RADIAN = (2 * Math.PI);\n    \n    private static double d2d(double a) {\n        return a % DEGREE;\n    }\n    private static double d2g(double a) {\n        return a * (GRADIAN / DEGREE);\n    }\n    private static double d2m(double a) {\n        return a * (MIL / DEGREE);\n    }\n    private static double d2r(double a) {\n        return a * (RADIAN / 360);\n    }\n\n    private static double g2d(double a) {\n        return a * (DEGREE / GRADIAN);\n    }\n    private static double g2g(double a) {\n        return a % GRADIAN;\n    }\n    private static double g2m(double a) {\n        return a * (MIL / GRADIAN);\n    }\n    private static double g2r(double a) {\n        return a * (RADIAN / GRADIAN);\n    }\n    \n    private static double m2d(double a) {\n        return a * (DEGREE / MIL);\n    }\n    private static double m2g(double a) {\n        return a * (GRADIAN / MIL);\n    }\n    private static double m2m(double a) {\n        return a % MIL;\n    }\n    private static double m2r(double a) {\n        return a * (RADIAN / MIL);\n    }\n    \n    private static double r2d(double a) {\n        return a * (DEGREE / RADIAN);\n    }\n    private static double r2g(double a) {\n        return a * (GRADIAN / RADIAN);\n    }\n    private static double r2m(double a) {\n        return a * (MIL / RADIAN);\n    }\n    private static double r2r(double a) {\n        return a % RADIAN;\n    }\n    \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n"}
{"id": 41519, "name": "Find common directory path", "Java": "public class CommonPath {\n\tpublic static String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\tfor(int i = 0; i < paths.length; i++){\n\t\t\tfolders[i] = paths[i].split(\"/\"); \n\t\t}\n\t\tfor(int j = 0; j < folders[0].length; j++){\n\t\t\tString thisFolder = folders[0][j]; \n\t\t\tboolean allMatched = true; \n\t\t\tfor(int i = 1; i < folders.length && allMatched; i++){ \n\t\t\t\tif(folders[i].length < j){ \n\t\t\t\t\tallMatched = false; \n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tallMatched &= folders[i][j].equals(thisFolder); \n\t\t\t}\n\t\t\tif(allMatched){ \n\t\t\t\tcommonPath += thisFolder + \"/\"; \n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn commonPath;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString[] paths = { \"/home/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths));\n\t\t\n\t\tString[] paths2 = { \"/hame/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths2));\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n"}
{"id": 41520, "name": "Verify distribution uniformity_Naive", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport java.util.function.IntSupplier;\n\npublic class Test {\n\n    static void distCheck(IntSupplier f, int nRepeats, double delta) {\n        Map<Integer, Integer> counts = new HashMap<>();\n\n        for (int i = 0; i < nRepeats; i++)\n            counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);\n\n        double target = nRepeats / (double) counts.size();\n        int deltaCount = (int) (delta / 100.0 * target);\n\n        counts.forEach((k, v) -> {\n            if (abs(target - v) >= deltaCount)\n                System.out.printf(\"distribution potentially skewed \"\n                        + \"for '%s': '%d'%n\", k, v);\n        });\n\n        counts.keySet().stream().sorted().forEach(k\n                -> System.out.printf(\"%d %d%n\", k, counts.get(k)));\n    }\n\n    public static void main(String[] a) {\n        distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 41521, "name": "Stirling numbers of the second kind", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 41522, "name": "Stirling numbers of the second kind", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 41523, "name": "Recaman's sequence", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 41524, "name": "Recaman's sequence", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 41525, "name": "Recaman's sequence", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 41526, "name": "Memory allocation", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n"}
{"id": 41527, "name": "Integer sequence", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 41528, "name": "Integer sequence", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 41529, "name": "Entropy_Narcissist", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n"}
{"id": 41530, "name": "Entropy_Narcissist", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n"}
{"id": 41531, "name": "DNS query", "Java": "import java.net.InetAddress;\nimport java.net.Inet4Address;\nimport java.net.Inet6Address;\nimport java.net.UnknownHostException;\n\nclass DnsQuery {\n    public static void main(String[] args) {\n        try {\n            InetAddress[] ipAddr = InetAddress.getAllByName(\"www.kame.net\");\n            for(int i=0; i < ipAddr.length ; i++) {\n                if (ipAddr[i] instanceof Inet4Address) {\n                    System.out.println(\"IPv4 : \" + ipAddr[i].getHostAddress());\n                } else if (ipAddr[i] instanceof Inet6Address) {\n                    System.out.println(\"IPv6 : \" + ipAddr[i].getHostAddress());\n                }\n            }\n        } catch (UnknownHostException uhe) {\n            System.err.println(\"unknown host\");\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 41532, "name": "Peano curve", "Java": "import java.io.*;\n\npublic class PeanoCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"peano_curve.svg\"))) {\n            PeanoCurve s = new PeanoCurve(writer);\n            final int length = 8;\n            s.currentAngle = 90;\n            s.currentX = length;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(656);\n            s.execute(rewrite(4));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private PeanoCurve(final Writer writer) {\n        this.writer = writer;\n    }\n\n    private void begin(final int size) throws IOException {\n        write(\"<svg xmlns='http:\n        write(\"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n        write(\"<path stroke-width='1' stroke='black' fill='none' d='\");\n    }\n\n    private void end() throws IOException {\n        write(\"'/>\\n</svg>\\n\");\n    }\n\n    private void execute(final String s) throws IOException {\n        write(\"M%g,%g\\n\", currentX, currentY);\n        for (int i = 0, n = s.length(); i < n; ++i) {\n            switch (s.charAt(i)) {\n                case 'F':\n                    line(lineLength);\n                    break;\n                case '+':\n                    turn(ANGLE);\n                    break;\n                case '-':\n                    turn(-ANGLE);\n                    break;\n            }\n        }\n    }\n\n    private void line(final double length) throws IOException {\n        final double theta = (Math.PI * currentAngle) / 180.0;\n        currentX += length * Math.cos(theta);\n        currentY += length * Math.sin(theta);\n        write(\"L%g,%g\\n\", currentX, currentY);\n    }\n\n    private void turn(final int angle) {\n        currentAngle = (currentAngle + angle) % 360;\n    }\n\n    private void write(final String format, final Object... args) throws IOException {\n        writer.write(String.format(format, args));\n    }\n\n    private static String rewrite(final int order) {\n        String s = \"L\";\n        for (int i = 0; i < order; ++i) {\n            final StringBuilder sb = new StringBuilder();\n            for (int j = 0, n = s.length(); j < n; ++j) {\n                final char ch = s.charAt(j);\n                if (ch == 'L')\n                    sb.append(\"LFRFL-F-RFLFR+F+LFRFL\");\n                else if (ch == 'R')\n                    sb.append(\"RFLFR+F+LFRFL-F-RFLFR\");\n                else\n                    sb.append(ch);\n            }\n            s = sb.toString();\n        }\n        return s;\n    }\n\n    private final Writer writer;\n    private double lineLength;\n    private double currentX;\n    private double currentY;\n    private int currentAngle;\n    private static final int ANGLE = 90;\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar points []gg.Point\n\nconst width = 81\n\nfunc peano(x, y, lg, i1, i2 int) {\n    if lg == 1 {\n        px := float64(width-x) * 10\n        py := float64(width-y) * 10\n        points = append(points, gg.Point{px, py})\n        return\n    }\n    lg /= 3\n    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)\n    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)\n    peano(x+lg, y+lg, lg, i1, 1-i2)\n    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)\n    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)\n    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)\n    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)\n    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)\n    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)\n}\n\nfunc main() {\n    peano(0, 0, width, 0, 0)\n    dc := gg.NewContext(820, 820)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for _, p := range points {\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetRGB(1, 0, 1) \n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"peano.png\")\n}\n"}
{"id": 41533, "name": "Seven-sided dice from five-sided dice", "Java": "import java.util.Random;\npublic class SevenSidedDice \n{\n\tprivate static final Random rnd = new Random();\n\tpublic static void main(String[] args)\n\t{\n\t\tSevenSidedDice now=new SevenSidedDice();\n\t\tSystem.out.println(\"Random number from 1 to 7: \"+now.seven());\n\t}\n\tint seven()\n\t{\n\t\tint v=21;\n\t\twhile(v>20)\n\t\t\tv=five()+five()*5-6;\n\t\treturn 1+v%7;\n\t}\n\tint five()\n\t{\n\t\treturn 1+rnd.nextInt(5);\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 41534, "name": "Solve the no connection puzzle", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\n\npublic class NoConnection {\n\n    \n    static int[][] links = {\n        {2, 3, 4}, \n        {3, 4, 5}, \n        {2, 4},    \n        {5},       \n        {2, 3, 4}, \n        {3, 4, 5}, \n    };\n\n    static int[] pegs = new int[8];\n\n    public static void main(String[] args) {\n\n        List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());\n        do {\n            Collections.shuffle(vals);\n            for (int i = 0; i < pegs.length; i++)\n                pegs[i] = vals.get(i);\n\n        } while (!solved());\n\n        printResult();\n    }\n\n    static boolean solved() {\n        for (int i = 0; i < links.length; i++)\n            for (int peg : links[i])\n                if (abs(pegs[i] - peg) == 1)\n                    return false;\n        return true;\n    }\n\n    static void printResult() {\n        System.out.printf(\"  %s %s%n\", pegs[0], pegs[1]);\n        System.out.printf(\"%s %s %s %s%n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n        System.out.printf(\"  %s %s%n\", pegs[6], pegs[7]);\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n"}
{"id": 41535, "name": "Magnanimous numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class MagnanimousNumbers {\n\n    public static void main(String[] args) {\n        runTask(\"Find and display the first 45 magnanimous numbers.\", 1, 45);\n        runTask(\"241st through 250th magnanimous numbers.\", 241, 250);\n        runTask(\"391st through 400th magnanimous numbers.\", 391, 400);\n    }\n    \n    private static void runTask(String message, int startN, int endN) {\n        int count = 0;\n        List<Integer> nums = new ArrayList<>();\n        for ( int n = 0 ; count < endN ; n++ ) {\n            if ( isMagnanimous(n) ) {\n                nums.add(n);\n                count++;\n            }\n        }\n        System.out.printf(\"%s%n\", message);\n        System.out.printf(\"%s%n%n\", nums.subList(startN-1, endN));\n    }\n    \n    private static boolean isMagnanimous(long n) {\n        if ( n >= 0 && n <= 9 ) {\n            return true;\n        }\n        long q = 11;\n        for ( long div = 10 ; q >= 10 ; div *= 10 ) {\n            q = n / div;\n            long r = n % div;\n            if ( ! isPrime(q+r) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n"}
{"id": 41536, "name": "Magnanimous numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class MagnanimousNumbers {\n\n    public static void main(String[] args) {\n        runTask(\"Find and display the first 45 magnanimous numbers.\", 1, 45);\n        runTask(\"241st through 250th magnanimous numbers.\", 241, 250);\n        runTask(\"391st through 400th magnanimous numbers.\", 391, 400);\n    }\n    \n    private static void runTask(String message, int startN, int endN) {\n        int count = 0;\n        List<Integer> nums = new ArrayList<>();\n        for ( int n = 0 ; count < endN ; n++ ) {\n            if ( isMagnanimous(n) ) {\n                nums.add(n);\n                count++;\n            }\n        }\n        System.out.printf(\"%s%n\", message);\n        System.out.printf(\"%s%n%n\", nums.subList(startN-1, endN));\n    }\n    \n    private static boolean isMagnanimous(long n) {\n        if ( n >= 0 && n <= 9 ) {\n            return true;\n        }\n        long q = 11;\n        for ( long div = 10 ; q >= 10 ; div *= 10 ) {\n            q = n / div;\n            long r = n % div;\n            if ( ! isPrime(q+r) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n"}
{"id": 41537, "name": "Extensible prime generator", "Java": "import java.util.*;\n\npublic class PrimeGenerator {\n    private int limit_;\n    private int index_ = 0;\n    private int increment_;\n    private int count_ = 0;\n    private List<Integer> primes_ = new ArrayList<>();\n    private BitSet sieve_ = new BitSet();\n    private int sieveLimit_ = 0;\n\n    public PrimeGenerator(int initialLimit, int increment) {\n        limit_ = nextOddNumber(initialLimit);\n        increment_ = increment;\n        primes_.add(2);\n        findPrimes(3);\n    }\n\n    public int nextPrime() {\n        if (index_ == primes_.size()) {\n            if (Integer.MAX_VALUE - increment_ < limit_)\n                return 0;\n            int start = limit_ + 2;\n            limit_ = nextOddNumber(limit_ + increment_);\n            primes_.clear();\n            findPrimes(start);\n        }\n        ++count_;\n        return primes_.get(index_++);\n    }\n\n    public int count() {\n        return count_;\n    }\n\n    private void findPrimes(int start) {\n        index_ = 0;\n        int newLimit = sqrt(limit_);\n        for (int p = 3; p * p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p));\n            for (; q <= newLimit; q += 2*p)\n                sieve_.set(q/2 - 1, true);\n        }\n        sieveLimit_ = newLimit;\n        int count = (limit_ - start)/2 + 1;\n        BitSet composite = new BitSet(count);\n        for (int p = 3; p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start;\n            q /= 2;\n            for (; q >= 0 && q < count; q += p)\n                composite.set(q, true);\n        }\n        for (int p = 0; p < count; ++p) {\n            if (!composite.get(p))\n                primes_.add(p * 2 + start);\n        }\n    }\n\n    private static int sqrt(int n) {\n        return nextOddNumber((int)Math.sqrt(n));\n    }\n\n    private static int nextOddNumber(int n) {\n        return 1 + 2 * (n/2);\n    }\n\n    public static void main(String[] args) {\n        PrimeGenerator pgen = new PrimeGenerator(20, 200000);\n        System.out.println(\"First 20 primes:\");\n        for (int i = 0; i < 20; ++i) {\n            if (i > 0)\n                System.out.print(\", \");\n            System.out.print(pgen.nextPrime());\n        }\n        System.out.println();\n        System.out.println(\"Primes between 100 and 150:\");\n        for (int i = 0; ; ) {\n            int prime = pgen.nextPrime();\n            if (prime > 150)\n                break;\n            if (prime >= 100) {\n                if (i++ != 0)\n                    System.out.print(\", \");\n                System.out.print(prime);\n            }\n        }\n        System.out.println();\n        int count = 0;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime > 8000)\n                break;\n            if (prime >= 7700)\n                ++count;\n        }\n        System.out.println(\"Number of primes between 7700 and 8000: \" + count);\n        int n = 10000;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime == 0) {\n                System.out.println(\"Can't generate any more primes.\");\n                break;\n            }\n            if (pgen.count() == n) {\n                System.out.println(n + \"th prime: \" + prime);\n                n *= 10;\n            }\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"fmt\"\n)\n\nfunc main() {\n    p := newP()\n    fmt.Print(\"First twenty: \")\n    for i := 0; i < 20; i++ {\n        fmt.Print(p(), \" \")\n    }\n    fmt.Print(\"\\nBetween 100 and 150: \")\n    n := p()\n    for n <= 100 {\n        n = p()\n    }\n    for ; n < 150; n = p() {\n        fmt.Print(n, \" \")\n    }\n    for n <= 7700 {\n        n = p()\n    }\n    c := 0\n    for ; n < 8000; n = p() {\n        c++\n    }\n    fmt.Println(\"\\nNumber beween 7,700 and 8,000:\", c)\n    p = newP()\n    for i := 1; i < 10000; i++ {\n        p()\n    }\n    fmt.Println(\"10,000th prime:\", p())\n}\n\nfunc newP() func() int {\n    n := 1\n    var pq pQueue\n    top := &pMult{2, 4, 0}\n    return func() int {\n        for {\n            n++\n            if n < top.pMult { \n                heap.Push(&pq, &pMult{prime: n, pMult: n * n})\n                top = pq[0]\n                return n\n            }\n            \n            for top.pMult == n {\n                top.pMult += top.prime\n                heap.Fix(&pq, 0)\n                top = pq[0]\n            }\n        }\n    }\n}\n\ntype pMult struct {\n    prime int\n    pMult int\n    index int\n}\n\ntype pQueue []*pMult\n\nfunc (q pQueue) Len() int           { return len(q) }\nfunc (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }\nfunc (q pQueue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n    q[i].index = i\n    q[j].index = j\n}\nfunc (p *pQueue) Push(x interface{}) {\n    q := *p\n    e := x.(*pMult)\n    e.index = len(q)\n    *p = append(q, e)\n}\nfunc (p *pQueue) Pop() interface{} {\n    q := *p\n    last := len(q) - 1\n    e := q[last]\n    *p = q[:last]\n    return e\n}\n"}
{"id": 41538, "name": "Rock-paper-scissors", "Java": "import java.util.Arrays;\nimport java.util.EnumMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Random;\n\npublic class RPS {\n\tpublic enum Item{\n\t\tROCK, PAPER, SCISSORS, ;\n\t\tpublic List<Item> losesToList;\n\t\tpublic boolean losesTo(Item other) {\n\t\t\treturn losesToList.contains(other);\n\t\t}\n\t\tstatic {\n\t\t\tSCISSORS.losesToList = Arrays.asList(ROCK);\n\t\t\tROCK.losesToList = Arrays.asList(PAPER);\n\t\t\tPAPER.losesToList = Arrays.asList(SCISSORS);\n\t\t\t\n                }\n\t}\n\t\n\tpublic final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{\n\t\tfor(Item item:Item.values())\n\t\t\tput(item, 1);\n\t}};\n\n\tprivate int totalThrows = Item.values().length;\n\n\tpublic static void main(String[] args){\n\t\tRPS rps = new RPS();\n\t\trps.run();\n\t}\n\n\tpublic void run() {\n\t\tScanner in = new Scanner(System.in);\n\t\tSystem.out.print(\"Make your choice: \");\n\t\twhile(in.hasNextLine()){\n\t\t\tItem aiChoice = getAIChoice();\n\t\t\tString input = in.nextLine();\n\t\t\tItem choice;\n\t\t\ttry{\n\t\t\t\tchoice = Item.valueOf(input.toUpperCase());\n\t\t\t}catch (IllegalArgumentException ex){\n\t\t\t\tSystem.out.println(\"Invalid choice\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcounts.put(choice, counts.get(choice) + 1);\n\t\t\ttotalThrows++;\n\t\t\tSystem.out.println(\"Computer chose: \" + aiChoice);\n\t\t\tif(aiChoice == choice){\n\t\t\t\tSystem.out.println(\"Tie!\");\n\t\t\t}else if(aiChoice.losesTo(choice)){\n\t\t\t\tSystem.out.println(\"You chose...wisely. You win!\");\n\t\t\t}else{\n\t\t\t\tSystem.out.println(\"You chose...poorly. You lose!\");\n\t\t\t}\n\t\t\tSystem.out.print(\"Make your choice: \");\n\t\t}\n\t}\n\n\tprivate static final Random rng = new Random();\n\tprivate Item getAIChoice() {\n\t\tint rand = rng.nextInt(totalThrows);\n\t\tfor(Map.Entry<Item, Integer> entry:counts.entrySet()){\n\t\t\tItem item = entry.getKey();\n\t\t\tint count = entry.getValue();\n\t\t\tif(rand < count){\n\t\t\t\tList<Item> losesTo = item.losesToList;\n\t\t\t\treturn losesTo.get(rng.nextInt(losesTo.size()));\n\t\t\t}\n\t\t\trand -= count;\n\t\t}\n\t\treturn null;\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n"}
{"id": 41539, "name": "Create a two-dimensional array at runtime", "Java": "import java.util.Scanner;\n\npublic class twoDimArray {\n  public static void main(String[] args) {\n        Scanner in = new Scanner(System.in);\n        \n        int nbr1 = in.nextInt();\n        int nbr2 = in.nextInt();\n        \n        double[][] array = new double[nbr1][nbr2];\n        array[0][0] = 42.0;\n        System.out.println(\"The number at place [0 0] is \" + array[0][0]);\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n"}
{"id": 41540, "name": "Chinese remainder theorem", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 41541, "name": "Chinese remainder theorem", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 41542, "name": "Vigenère cipher_Cryptanalysis", "Java": "public class Vig{\nstatic String encodedMessage =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n \nfinal static double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n \n\npublic static void main(String[] args) {\n    int lenghtOfEncodedMessage = encodedMessage.length();\n    char[] encoded = new char [lenghtOfEncodedMessage] ;\n    char[] key =  new char [lenghtOfEncodedMessage] ;\n\n    encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0);\n    int txt[] = new int[lenghtOfEncodedMessage];\n    int len = 0, j;\n\n    double fit, best_fit = 1e100;\n \n    for (j = 0; j < lenghtOfEncodedMessage; j++)\n        if (Character.isUpperCase(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n \n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        System.out.printf(\"%f, key length: %2d \", fit, j);\n            System.out.print(key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            System.out.print(\" <--- best so far\");\n        }\n        System.out.print(\"\\n\");\n\n    }\n}\n\n\n    static String decrypt(String text, final String key) {\n        String res = \"\";\n        text = text.toUpperCase();\n        for (int i = 0, j = 0; i < text.length(); i++) {\n            char c = text.charAt(i);\n            if (c < 'A' || c > 'Z') continue;\n            res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n            j = ++j % key.length();\n        }\n        return res;\n    }\n\nstatic int best_match(final double []a, final double []b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n \n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n \n    return best_rotate;\n}\n \nstatic double freq_every_nth(final int []msg, int len, int interval, char[] key) {\n    double sum, d, ret;\n    double  [] accu = new double [26];\n    double  [] out = new double [26];\n    int i, j, rot;\n \n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n\trot = best_match(out, freq);\n\ttry{\n            key[j] = (char)(rot + 'A');\n\t} catch (Exception e) {\n\t\tSystem.out.print(e.getMessage());\n\t}\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n \n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n \n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n \n    key[interval] = '\\0';\n    return ret;\n}\n \n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar encoded = \n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [26]float64{\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n}\n\nfunc sum(a []float64) (sum float64) {\n    for _, f := range a {\n        sum += f\n    }\n    return\n}\n\nfunc bestMatch(a []float64) int {\n    sum := sum(a)\n    bestFit, bestRotate := 1e100, 0\n    for rotate := 0; rotate < 26; rotate++ {\n        fit := 0.0\n        for i := 0; i < 26; i++ {\n            d := a[(i+rotate)%26]/sum - freq[i]\n            fit += d * d / freq[i]\n        }\n        if fit < bestFit {\n            bestFit, bestRotate = fit, rotate\n        }\n    }\n    return bestRotate\n}\n\nfunc freqEveryNth(msg []int, key []byte) float64 {\n    l := len(msg)\n    interval := len(key)\n    out := make([]float64, 26)\n    accu := make([]float64, 26)\n    for j := 0; j < interval; j++ {\n        for k := 0; k < 26; k++ {\n            out[k] = 0.0\n        }\n        for i := j; i < l; i += interval {\n            out[msg[i]]++\n        }\n        rot := bestMatch(out)\n        key[j] = byte(rot + 65)\n        for i := 0; i < 26; i++ {\n            accu[i] += out[(i+rot)%26]\n        }\n    }\n    sum := sum(accu)\n    ret := 0.0\n    for i := 0; i < 26; i++ {\n        d := accu[i]/sum - freq[i]\n        ret += d * d / freq[i]\n    }\n    return ret\n}\n\nfunc decrypt(text, key string) string {\n    var sb strings.Builder\n    ki := 0\n    for _, c := range text {\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        ci := (c - rune(key[ki]) + 26) % 26\n        sb.WriteRune(ci + 65)\n        ki = (ki + 1) % len(key)\n    }\n    return sb.String()\n}\n\nfunc main() {\n    enc := strings.Replace(encoded, \" \", \"\", -1)\n    txt := make([]int, len(enc))\n    for i := 0; i < len(txt); i++ {\n        txt[i] = int(enc[i] - 'A')\n    }\n    bestFit, bestKey := 1e100, \"\"\n    fmt.Println(\"  Fit     Length   Key\")\n    for j := 1; j <= 26; j++ {\n        key := make([]byte, j)\n        fit := freqEveryNth(txt, key)\n        sKey := string(key)\n        fmt.Printf(\"%f    %2d     %s\", fit, j, sKey)\n        if fit < bestFit {\n            bestFit, bestKey = fit, sKey\n            fmt.Print(\" <--- best so far\")\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nBest key :\", bestKey)\n    fmt.Printf(\"\\nDecrypted text:\\n%s\\n\", decrypt(enc, bestKey))\n}\n"}
{"id": 41543, "name": "Pi", "Java": "import java.math.BigInteger ;\n\npublic class Pi {\n  final BigInteger TWO = BigInteger.valueOf(2) ;\n  final BigInteger THREE = BigInteger.valueOf(3) ;\n  final BigInteger FOUR = BigInteger.valueOf(4) ;\n  final BigInteger SEVEN = BigInteger.valueOf(7) ;\n\n  BigInteger q = BigInteger.ONE ;\n  BigInteger r = BigInteger.ZERO ;\n  BigInteger t = BigInteger.ONE ;\n  BigInteger k = BigInteger.ONE ;\n  BigInteger n = BigInteger.valueOf(3) ;\n  BigInteger l = BigInteger.valueOf(3) ;\n\n  public void calcPiDigits(){\n    BigInteger nn, nr ;\n    boolean first = true ;\n    while(true){\n        if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){\n          System.out.print(n) ;\n          if(first){System.out.print(\".\") ; first = false ;}\n          nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ;\n          n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ;\n          q = q.multiply(BigInteger.TEN) ;\n          r = nr ;\n          System.out.flush() ;\n        }else{\n          nr = TWO.multiply(q).add(r).multiply(l) ;\n          nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ;\n          q = q.multiply(k) ;\n          t = t.multiply(l) ;\n          l = l.add(TWO) ;\n          k = k.add(BigInteger.ONE) ;\n          n = nn ;\n          r = nr ;\n        }\n    }\n  }\n\n  public static void main(String[] args) {\n    Pi p = new Pi() ;\n    p.calcPiDigits() ;\n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n"}
{"id": 41544, "name": "Hofstadter Q sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n"}
{"id": 41545, "name": "Hofstadter Q sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n"}
{"id": 41546, "name": "Y combinator", "Java": "import java.util.function.Function;\n\npublic interface YCombinator {\n  interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }\n  public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {\n    RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));\n    return r.apply(r);\n  }\n\n  public static void main(String... arguments) {\n    Function<Integer,Integer> fib = Y(f -> n ->\n      (n <= 2)\n        ? 1\n        : (f.apply(n - 1) + f.apply(n - 2))\n    );\n    Function<Integer,Integer> fac = Y(f -> n ->\n      (n <= 1)\n        ? 1\n        : (n * f.apply(n - 1))\n    );\n\n    System.out.println(\"fib(10) = \" + fib.apply(10));\n    System.out.println(\"fac(10) = \" + fac.apply(10));\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n"}
{"id": 41547, "name": "Y combinator", "Java": "import java.util.function.Function;\n\npublic interface YCombinator {\n  interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }\n  public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {\n    RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));\n    return r.apply(r);\n  }\n\n  public static void main(String... arguments) {\n    Function<Integer,Integer> fib = Y(f -> n ->\n      (n <= 2)\n        ? 1\n        : (f.apply(n - 1) + f.apply(n - 2))\n    );\n    Function<Integer,Integer> fac = Y(f -> n ->\n      (n <= 1)\n        ? 1\n        : (n * f.apply(n - 1))\n    );\n\n    System.out.println(\"fib(10) = \" + fib.apply(10));\n    System.out.println(\"fac(10) = \" + fac.apply(10));\n  }\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n"}
{"id": 41548, "name": "Return multiple values", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\n\npublic class RReturnMultipleVals {\n  public static final String K_lipsum = \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n  public static final Long   K_1024   = 1024L;\n  public static final String L        = \"L\";\n  public static final String R        = \"R\";\n\n  \n  public static void main(String[] args) throws NumberFormatException{\n    Long nv_;\n    String sv_;\n    switch (args.length) {\n      case 0:\n        nv_ = K_1024;\n        sv_ = K_lipsum;\n        break;\n      case 1:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = K_lipsum;\n        break;\n      case 2:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        break;\n      default:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        for (int ix = 2; ix < args.length; ++ix) {\n          sv_ = sv_ + \" \" + args[ix];\n        }\n        break;\n    }\n\n    RReturnMultipleVals lcl = new RReturnMultipleVals();\n\n    Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); \n    System.out.println(\"Results extracted from a composite object:\");\n    System.out.printf(\"%s, %s%n%n\", rvp.getLeftVal(), rvp.getRightVal());\n\n    List<Object> rvl = lcl.getPairFromList(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"List\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvl.get(0), rvl.get(1));\n\n    Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"Map\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvm.get(L), rvm.get(R));\n  }\n  \n  \n  \n  public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {\n    return new Pair<T, U>(vl_, vr_);\n  }\n  \n  \n  \n  public List<Object> getPairFromList(Object nv_, Object sv_) {\n    List<Object> rset = new ArrayList<Object>();\n    rset.add(nv_);\n    rset.add(sv_);\n    return rset;\n  }\n  \n  \n  \n  public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {\n    Map<String, Object> rset = new HashMap<String, Object>();\n    rset.put(L, nv_);\n    rset.put(R, sv_);\n    return rset;\n  }\n\n  \n  private static class Pair<L, R> {\n    private L leftVal;\n    private R rightVal;\n\n    public Pair(L nv_, R sv_) {\n      setLeftVal(nv_);\n      setRightVal(sv_);\n    }\n    public void setLeftVal(L nv_) {\n      leftVal = nv_;\n    }\n    public L getLeftVal() {\n      return leftVal;\n    }\n    public void setRightVal(R sv_) {\n      rightVal = sv_;\n    }\n    public R getRightVal() {\n      return rightVal;\n    }\n  }\n}\n", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n"}
{"id": 41549, "name": "Van Eck sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 41550, "name": "Van Eck sequence", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 41551, "name": "FTP", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport org.apache.commons.net.ftp.FTP;\nimport org.apache.commons.net.ftp.FTPClient;\nimport org.apache.commons.net.ftp.FTPFile;\nimport org.apache.commons.net.ftp.FTPReply;\n\npublic class FTPconn {\n\n    public static void main(String[] args) throws IOException {\n        String server = \"ftp.hq.nasa.gov\";\n        int port = 21;\n        String user = \"anonymous\";\n        String pass = \"ftptest@example.com\";\n\n        OutputStream output = null;\n\n        FTPClient ftpClient = new FTPClient();\n        try {\n            ftpClient.connect(server, port);\n\n            serverReply(ftpClient);\n\n            int replyCode = ftpClient.getReplyCode();\n            if (!FTPReply.isPositiveCompletion(replyCode)) {\n                System.out.println(\"Failure. Server reply code: \" + replyCode);\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            if (!ftpClient.login(user, pass)) {\n                System.out.println(\"Could not login to the server.\");\n                return;\n            }\n\n            String dir = \"pub/issoutreach/Living in Space Stories (MP3 Files)/\";\n            if (!ftpClient.changeWorkingDirectory(dir)) {\n                System.out.println(\"Change directory failed.\");\n                return;\n            }\n\n            ftpClient.enterLocalPassiveMode();\n\n            for (FTPFile file : ftpClient.listFiles())\n                System.out.println(file);\n\n            String filename = \"Can People go to Mars.mp3\";\n            output = new FileOutputStream(filename);\n\n            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);\n            if (!ftpClient.retrieveFile(filename, output)) {\n                System.out.println(\"Retrieving file failed\");\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            ftpClient.logout();\n\n        } finally {\n            if (output != null)\n                output.close();\n        }\n    }\n\n    private static void serverReply(FTPClient ftpClient) {\n        for (String reply : ftpClient.getReplyStrings()) {\n            System.out.println(reply);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n"}
{"id": 41552, "name": "FTP", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport org.apache.commons.net.ftp.FTP;\nimport org.apache.commons.net.ftp.FTPClient;\nimport org.apache.commons.net.ftp.FTPFile;\nimport org.apache.commons.net.ftp.FTPReply;\n\npublic class FTPconn {\n\n    public static void main(String[] args) throws IOException {\n        String server = \"ftp.hq.nasa.gov\";\n        int port = 21;\n        String user = \"anonymous\";\n        String pass = \"ftptest@example.com\";\n\n        OutputStream output = null;\n\n        FTPClient ftpClient = new FTPClient();\n        try {\n            ftpClient.connect(server, port);\n\n            serverReply(ftpClient);\n\n            int replyCode = ftpClient.getReplyCode();\n            if (!FTPReply.isPositiveCompletion(replyCode)) {\n                System.out.println(\"Failure. Server reply code: \" + replyCode);\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            if (!ftpClient.login(user, pass)) {\n                System.out.println(\"Could not login to the server.\");\n                return;\n            }\n\n            String dir = \"pub/issoutreach/Living in Space Stories (MP3 Files)/\";\n            if (!ftpClient.changeWorkingDirectory(dir)) {\n                System.out.println(\"Change directory failed.\");\n                return;\n            }\n\n            ftpClient.enterLocalPassiveMode();\n\n            for (FTPFile file : ftpClient.listFiles())\n                System.out.println(file);\n\n            String filename = \"Can People go to Mars.mp3\";\n            output = new FileOutputStream(filename);\n\n            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);\n            if (!ftpClient.retrieveFile(filename, output)) {\n                System.out.println(\"Retrieving file failed\");\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            ftpClient.logout();\n\n        } finally {\n            if (output != null)\n                output.close();\n        }\n    }\n\n    private static void serverReply(FTPClient ftpClient) {\n        for (String reply : ftpClient.getReplyStrings()) {\n            System.out.println(reply);\n        }\n    }\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n"}
{"id": 41553, "name": "24 game", "Java": "import java.util.*;\n\npublic class Game24 {\n    static Random r = new Random();\n\n    public static void main(String[] args) {\n\n        int[] digits = randomDigits();\n        Scanner in = new Scanner(System.in);\n\n        System.out.print(\"Make 24 using these digits: \");\n        System.out.println(Arrays.toString(digits));\n        System.out.print(\"> \");\n\n        Stack<Float> s = new Stack<>();\n        long total = 0;\n        for (char c : in.nextLine().toCharArray()) {\n            if ('0' <= c && c <= '9') {\n                int d = c - '0';\n                total += (1 << (d * 5));\n                s.push((float) d);\n            } else if (\"+/-*\".indexOf(c) != -1) {\n                s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        }\n        if (tallyDigits(digits) != total)\n            System.out.print(\"Not the same digits. \");\n        else if (Math.abs(24 - s.peek()) < 0.001F)\n            System.out.println(\"Correct!\");\n        else\n            System.out.print(\"Not correct.\");\n    }\n\n    static float applyOperator(float a, float b, char c) {\n        switch (c) {\n            case '+':\n                return a + b;\n            case '-':\n                return b - a;\n            case '*':\n                return a * b;\n            case '/':\n                return b / a;\n            default:\n                return Float.NaN;\n        }\n    }\n\n    static long tallyDigits(int[] a) {\n        long total = 0;\n        for (int i = 0; i < 4; i++)\n            total += (1 << (a[i] * 5));\n        return total;\n    }\n\n    static int[] randomDigits() {        \n        int[] result = new int[4];\n        for (int i = 0; i < 4; i++)\n            result[i] = r.nextInt(9) + 1;\n        return result;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n"}
{"id": 41554, "name": "24 game", "Java": "import java.util.*;\n\npublic class Game24 {\n    static Random r = new Random();\n\n    public static void main(String[] args) {\n\n        int[] digits = randomDigits();\n        Scanner in = new Scanner(System.in);\n\n        System.out.print(\"Make 24 using these digits: \");\n        System.out.println(Arrays.toString(digits));\n        System.out.print(\"> \");\n\n        Stack<Float> s = new Stack<>();\n        long total = 0;\n        for (char c : in.nextLine().toCharArray()) {\n            if ('0' <= c && c <= '9') {\n                int d = c - '0';\n                total += (1 << (d * 5));\n                s.push((float) d);\n            } else if (\"+/-*\".indexOf(c) != -1) {\n                s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        }\n        if (tallyDigits(digits) != total)\n            System.out.print(\"Not the same digits. \");\n        else if (Math.abs(24 - s.peek()) < 0.001F)\n            System.out.println(\"Correct!\");\n        else\n            System.out.print(\"Not correct.\");\n    }\n\n    static float applyOperator(float a, float b, char c) {\n        switch (c) {\n            case '+':\n                return a + b;\n            case '-':\n                return b - a;\n            case '*':\n                return a * b;\n            case '/':\n                return b / a;\n            default:\n                return Float.NaN;\n        }\n    }\n\n    static long tallyDigits(int[] a) {\n        long total = 0;\n        for (int i = 0; i < 4; i++)\n            total += (1 << (a[i] * 5));\n        return total;\n    }\n\n    static int[] randomDigits() {        \n        int[] result = new int[4];\n        for (int i = 0; i < 4; i++)\n            result[i] = r.nextInt(9) + 1;\n        return result;\n    }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n"}
{"id": 41555, "name": "Loops_Continue", "Java": "for(int i = 1;i <= 10; i++){\n   System.out.print(i);\n   if(i % 5 == 0){\n      System.out.println();\n      continue;\n   }\n   System.out.print(\", \");\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 10; i++ {\n        fmt.Printf(\"%d\", i)\n        if i%5 == 0 {\n            fmt.Printf(\"\\n\")\n            continue\n        }\n        fmt.Printf(\", \")\n    }\n}\n"}
{"id": 41556, "name": "Colour bars_Display", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\n\npublic class ColorFrame extends JFrame {\n\tpublic ColorFrame(int width, int height) {\n\t\tthis.setDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tthis.setSize(width, height);\n\t\tthis.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tColor[] colors = { Color.black, Color.red, Color.green, Color.blue,\n\t\t\t\tColor.pink, Color.CYAN, Color.yellow, Color.white };\n\n\t\tfor (int i = 0; i < colors.length; i++) {\n\t\t\tg.setColor(colors[i]);\n\t\t\tg.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()\n\t\t\t\t\t/ colors.length, this.getHeight());\n\t\t}\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tnew ColorFrame(200, 200);\n\t}\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 41557, "name": "Colour bars_Display", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\n\npublic class ColorFrame extends JFrame {\n\tpublic ColorFrame(int width, int height) {\n\t\tthis.setDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tthis.setSize(width, height);\n\t\tthis.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tColor[] colors = { Color.black, Color.red, Color.green, Color.blue,\n\t\t\t\tColor.pink, Color.CYAN, Color.yellow, Color.white };\n\n\t\tfor (int i = 0; i < colors.length; i++) {\n\t\t\tg.setColor(colors[i]);\n\t\t\tg.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()\n\t\t\t\t\t/ colors.length, this.getHeight());\n\t\t}\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tnew ColorFrame(200, 200);\n\t}\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 41558, "name": "LU decomposition", "Java": "import static java.util.Arrays.stream;\nimport java.util.Locale;\nimport static java.util.stream.IntStream.range;\n\npublic class Test {\n\n    static double dotProduct(double[] a, double[] b) {\n        return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum();\n    }\n\n    static double[][] matrixMul(double[][] A, double[][] B) {\n        double[][] result = new double[A.length][B[0].length];\n        double[] aux = new double[B.length];\n\n        for (int j = 0; j < B[0].length; j++) {\n\n            for (int k = 0; k < B.length; k++)\n                aux[k] = B[k][j];\n\n            for (int i = 0; i < A.length; i++)\n                result[i][j] = dotProduct(A[i], aux);\n        }\n        return result;\n    }\n\n    static double[][] pivotize(double[][] m) {\n        int n = m.length;\n        double[][] id = range(0, n).mapToObj(j -> range(0, n)\n                .mapToDouble(i -> i == j ? 1 : 0).toArray())\n                .toArray(double[][]::new);\n\n        for (int i = 0; i < n; i++) {\n            double maxm = m[i][i];\n            int row = i;\n            for (int j = i; j < n; j++)\n                if (m[j][i] > maxm) {\n                    maxm = m[j][i];\n                    row = j;\n                }\n\n            if (i != row) {\n                double[] tmp = id[i];\n                id[i] = id[row];\n                id[row] = tmp;\n            }\n        }\n        return id;\n    }\n\n    static double[][][] lu(double[][] A) {\n        int n = A.length;\n        double[][] L = new double[n][n];\n        double[][] U = new double[n][n];\n        double[][] P = pivotize(A);\n        double[][] A2 = matrixMul(P, A);\n\n        for (int j = 0; j < n; j++) {\n            L[j][j] = 1;\n            for (int i = 0; i < j + 1; i++) {\n                double s1 = 0;\n                for (int k = 0; k < i; k++)\n                    s1 += U[k][j] * L[i][k];\n                U[i][j] = A2[i][j] - s1;\n            }\n            for (int i = j; i < n; i++) {\n                double s2 = 0;\n                for (int k = 0; k < j; k++)\n                    s2 += U[k][j] * L[i][k];\n                L[i][j] = (A2[i][j] - s2) / U[j][j];\n            }\n        }\n        return new double[][][]{L, U, P};\n    }\n\n    static void print(double[][] m) {\n        stream(m).forEach(a -> {\n            stream(a).forEach(n -> System.out.printf(Locale.US, \"%5.1f \", n));\n            System.out.println();\n        });\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}};\n\n        double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1},\n        {2.0, 5, 7, 1}};\n\n        for (double[][] m : lu(a))\n            print(m);\n\n        System.out.println();\n\n        for (double[][] m : lu(b))\n            print(m);\n    }\n}\n", "Go": "package main\n\nimport \"fmt\"\n    \ntype matrix [][]float64\n\nfunc zero(n int) matrix {\n    r := make([][]float64, n)\n    a := make([]float64, n*n)\n    for i := range r {\n        r[i] = a[n*i : n*(i+1)]\n    } \n    return r \n}\n    \nfunc eye(n int) matrix {\n    r := zero(n)\n    for i := range r {\n        r[i][i] = 1\n    }\n    return r\n}   \n    \nfunc (m matrix) print(label string) {\n    if label > \"\" {\n        fmt.Printf(\"%s:\\n\", label)\n    }\n    for _, r := range m {\n        for _, e := range r {\n            fmt.Printf(\" %9.5f\", e)\n        }\n        fmt.Println()\n    }\n}\n\nfunc (a matrix) pivotize() matrix { \n    p := eye(len(a))\n    for j, r := range a {\n        max := r[j] \n        row := j\n        for i := j; i < len(a); i++ {\n            if a[i][j] > max {\n                max = a[i][j]\n                row = i\n            }\n        }\n        if j != row {\n            \n            p[j], p[row] = p[row], p[j]\n        }\n    } \n    return p\n}\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    r := zero(len(m1))\n    for i, r1 := range m1 {\n        for j := range m2 {\n            for k := range m1 {\n                r[i][j] += r1[k] * m2[k][j]\n            }\n        }\n    }\n    return r\n}\n\nfunc (a matrix) lu() (l, u, p matrix) {\n    l = zero(len(a))\n    u = zero(len(a))\n    p = a.pivotize()\n    a = p.mul(a)\n    for j := range a {\n        l[j][j] = 1\n        for i := 0; i <= j; i++ {\n            sum := 0.\n            for k := 0; k < i; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            u[i][j] = a[i][j] - sum\n        }\n        for i := j; i < len(a); i++ {\n            sum := 0.\n            for k := 0; k < j; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            l[i][j] = (a[i][j] - sum) / u[j][j]\n        }\n    }\n    return\n}\n\nfunc main() {\n    showLU(matrix{\n        {1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}})\n    showLU(matrix{\n        {11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}})\n}\n\nfunc showLU(a matrix) {\n    a.print(\"\\na\")\n    l, u, p := a.lu()\n    l.print(\"l\")\n    u.print(\"u\") \n    p.print(\"p\") \n}\n"}
{"id": 41559, "name": "General FizzBuzz", "Java": "public class FizzBuzz {\n\n    public static void main(String[] args) {\n        Sound[] sounds = {new Sound(3, \"Fizz\"), new Sound(5, \"Buzz\"),  new Sound(7, \"Baxx\")};\n        for (int i = 1; i <= 20; i++) {\n            StringBuilder sb = new StringBuilder();\n            for (Sound sound : sounds) {\n                sb.append(sound.generate(i));\n            }\n            System.out.println(sb.length() == 0 ? i : sb.toString());\n        }\n    }\n\n    private static class Sound {\n        private final int trigger;\n        private final String onomatopoeia;\n\n        public Sound(int trigger, String onomatopoeia) {\n            this.trigger = trigger;\n            this.onomatopoeia = onomatopoeia;\n        }\n\n        public String generate(int i) {\n            return i % trigger == 0 ? onomatopoeia : \"\";\n        }\n\n    }\n\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n)\n\nconst numbers = 3\n\nfunc main() {\n\n\t\n\tmax := 20\n\twords := map[int]string{\n\t\t3: \"Fizz\",\n\t\t5: \"Buzz\",\n\t\t7: \"Baxx\",\n\t}\n\tkeys := []int{3, 5, 7}\n\tdivisible := false\n\tfor i := 1; i <= max; i++ {\n\t\tfor _, n := range keys {\n\t\t\tif i % n == 0 {\n\t\t\t\tfmt.Print(words[n])\n\t\t\t\tdivisible = true\n\t\t\t}\n\t\t}\n\t\tif !divisible {\n\t\t\tfmt.Print(i)\n\t\t}\n\t\tfmt.Println()\n\t\tdivisible = false\n\t}\n\n}\n"}
{"id": 41560, "name": "Bitwise operations", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 41561, "name": "Dragon curve", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n"}
{"id": 41562, "name": "Doubly-linked list_Element insertion", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n"}
{"id": 41563, "name": "Quickselect algorithm", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n"}
{"id": 41564, "name": "Non-decimal radices_Convert", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n", "Python": "i = int('1a',16)  \n"}
{"id": 41565, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 41566, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 41567, "name": "Classes", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 41568, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41569, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41570, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 41571, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 41572, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 41573, "name": "Anonymous recursion", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 41574, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 41575, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 41576, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 41577, "name": "Create a file", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 41578, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n"}
{"id": 41579, "name": "Enforced immutability", "C#": "readonly DateTime now = DateTime.Now;\n", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n"}
{"id": 41580, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 41581, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 41582, "name": "Spiral matrix", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n"}
{"id": 41583, "name": "Faulhaber's triangle", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 41584, "name": "Faulhaber's triangle", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 41585, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41586, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 41587, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 41588, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 41589, "name": "User input_Text", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 41590, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 41591, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 41592, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 41593, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 41594, "name": "First-class functions", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n"}
{"id": 41595, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 41596, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 41597, "name": "XML_Output", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n"}
{"id": 41598, "name": "Regular expressions", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 41599, "name": "Guess the number_With feedback (player)", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n"}
{"id": 41600, "name": "Hash from two arrays", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 41601, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 41602, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n"}
{"id": 41603, "name": "Animate a pendulum", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n"}
{"id": 41604, "name": "Sorting algorithms_Heapsort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n"}
{"id": 41605, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 41606, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 41607, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 41608, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 41609, "name": "Sierpinski carpet", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 41610, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 41611, "name": "Merge and aggregate datasets", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n"}
{"id": 41612, "name": "Merge and aggregate datasets", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n"}
{"id": 41613, "name": "Euler method", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n"}
{"id": 41614, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 41615, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 41616, "name": "JortSort", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n"}
{"id": 41617, "name": "Leap year", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 41618, "name": "Sort numbers lexicographically", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n"}
{"id": 41619, "name": "Number names", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 41620, "name": "Compare length of two strings", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n"}
{"id": 41621, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 41622, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "Python": "next = str(int('123') + 1)\n"}
{"id": 41623, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 41624, "name": "Averages_Arithmetic mean", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 41625, "name": "Entropy", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n"}
{"id": 41626, "name": "Tokenize a string with escaping", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n"}
{"id": 41627, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "Python": "print \"Hello world!\"\n"}
{"id": 41628, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "Python": "print \"Hello world!\"\n"}
{"id": 41629, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 41630, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 41631, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 41632, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 41633, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 41634, "name": "Singly-linked list_Traversal", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n", "Python": "for node in lst:\n    print node.value\n"}
{"id": 41635, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 41636, "name": "Delete a file", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 41637, "name": "Discordian date", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n"}
{"id": 41638, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 41639, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 41640, "name": "String interpolation (included)", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 41641, "name": "Partition function P", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n"}
{"id": 41642, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 41643, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 41644, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 41645, "name": "Take notes on the command line", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 41646, "name": "Angles (geometric), normalization and conversion", "C#": "using System;\n\npublic static class Angles\n{\n    public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);\n\n    public static void Print(params double[] angles) {\n        string[] names = { \"Degrees\", \"Gradians\", \"Mils\", \"Radians\" };\n        Func<double, double> rnd = a => Math.Round(a, 4);\n        Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };\n\n        Func<double, double>[,] convert = {\n            { a => a, DegToGrad, DegToMil, DegToRad },\n            { GradToDeg, a => a, GradToMil, GradToRad },\n            { MilToDeg, MilToGrad, a => a, MilToRad },\n            { RadToDeg, RadToGrad, RadToMil, a => a }\n        };\n\n        Console.WriteLine($@\"{\"Angle\",-12}{\"Normalized\",-12}{\"Unit\",-12}{\n            \"Degrees\",-12}{\"Gradians\",-12}{\"Mils\",-12}{\"Radians\",-12}\");\n\n        foreach (double angle in angles) {\n            for (int i = 0; i < 4; i++) {\n                double nAngle = normal[i](angle);\n\n                Console.WriteLine($@\"{\n                    rnd(angle),-12}{\n                    rnd(nAngle),-12}{\n                    names[i],-12}{\n                    rnd(convert[i, 0](nAngle)),-12}{\n                    rnd(convert[i, 1](nAngle)),-12}{\n                    rnd(convert[i, 2](nAngle)),-12}{\n                    rnd(convert[i, 3](nAngle)),-12}\");\n            }\n        }\n    }\n\n    public static double NormalizeDeg(double angle) => Normalize(angle, 360);\n    public static double NormalizeGrad(double angle) => Normalize(angle, 400);\n    public static double NormalizeMil(double angle) => Normalize(angle, 6400);\n    public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);\n\n    private static double Normalize(double angle, double N) {\n        while (angle <= -N) angle += N;\n        while (angle >= N) angle -= N;\n        return angle;\n    }\n\n    public static double DegToGrad(double angle) => angle * 10 / 9;\n    public static double DegToMil(double angle) => angle * 160 / 9;\n    public static double DegToRad(double angle) => angle * Math.PI / 180;\n    \n    public static double GradToDeg(double angle) => angle * 9 / 10;\n    public static double GradToMil(double angle) => angle * 16;\n    public static double GradToRad(double angle) => angle * Math.PI / 200;\n    \n    public static double MilToDeg(double angle) => angle * 9 / 160;\n    public static double MilToGrad(double angle) => angle / 16;\n    public static double MilToRad(double angle) => angle * Math.PI / 3200;\n    \n    public static double RadToDeg(double angle) => angle * 180 / Math.PI;\n    public static double RadToGrad(double angle) => angle * 200 / Math.PI;\n    public static double RadToMil(double angle) => angle * 3200 / Math.PI;\n}\n", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n"}
{"id": 41647, "name": "Find common directory path", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n"}
{"id": 41648, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 41649, "name": "Recaman's sequence", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n"}
{"id": 41650, "name": "Memory allocation", "C#": "using System;\nusing System.Runtime.InteropServices;\n\npublic unsafe class Program\n{\n    public static unsafe void HeapMemory()\n    {\n        const int HEAP_ZERO_MEMORY = 0x00000008;\n        const int size = 1000;\n        int ph = GetProcessHeap();\n        void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);\n        if (pointer == null)\n            throw new OutOfMemoryException();\n        Console.WriteLine(HeapSize(ph, 0, pointer));\n        HeapFree(ph, 0, pointer);\n    }\n\n    public static unsafe void StackMemory()\n    {\n        byte* buffer = stackalloc byte[1000];\n        \n    }\n    public static void Main(string[] args)\n    {\n        HeapMemory();\n        StackMemory();\n    }\n    [DllImport(\"kernel32\")]\n    static extern void* HeapAlloc(int hHeap, int flags, int size);\n    [DllImport(\"kernel32\")]\n    static extern bool HeapFree(int hHeap, int flags, void* block);\n    [DllImport(\"kernel32\")]\n    static extern int GetProcessHeap();\n    [DllImport(\"kernel32\")]\n    static extern int HeapSize(int hHeap, int flags, void* block);\n\n}\n", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n"}
{"id": 41651, "name": "Tic-tac-toe", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaTicTacToe\n{\n  class Program\n  {\n\n    \n    static string[][] Players = new string[][] { \n      new string[] { \"COMPUTER\", \"X\" }, \n      new string[] { \"HUMAN\", \"O\" }     \n    };\n\n    const int Unplayed = -1;\n    const int Computer = 0;\n    const int Human = 1;\n\n    \n    static int[] GameBoard = new int[9];\n\n    static int[] corners = new int[] { 0, 2, 6, 8 };\n\n    static int[][] wins = new int[][] { \n      new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, \n      new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, \n      new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };\n\n\n    \n    static void Main(string[] args)\n    {\n      while (true)\n      {\n        Console.Clear();\n        Console.WriteLine(\"Welcome to Rosetta Code Tic-Tac-Toe for C#.\");\n        initializeGameBoard();\n        displayGameBoard();\n        int currentPlayer = rnd.Next(0, 2);  \n        Console.WriteLine(\"The first move goes to {0} who is playing {1}s.\\n\", playerName(currentPlayer), playerToken(currentPlayer));\n        while (true)\n        {\n          int thisMove = getMoveFor(currentPlayer);\n          if (thisMove == Unplayed)\n          {\n            Console.WriteLine(\"{0}, you've quit the game ... am I that good?\", playerName(currentPlayer));\n            break;\n          }\n          playMove(thisMove, currentPlayer);\n          displayGameBoard();\n          if (isGameWon())\n          {\n            Console.WriteLine(\"{0} has won the game!\", playerName(currentPlayer));\n            break;\n          }\n          else if (isGameTied())\n          {\n            Console.WriteLine(\"Cat game ... we have a tie.\");\n            break;\n          }\n          currentPlayer = getNextPlayer(currentPlayer);\n        }\n        if (!playAgain())\n          return;\n      }\n    }\n\n    \n    static int getMoveFor(int player)\n    {\n      if (player == Human)\n        return getManualMove(player);\n      else\n      {\n        \n        \n        int selectedMove = getSemiRandomMove(player);\n        \n        Console.WriteLine(\"{0} selects position {1}.\", playerName(player), selectedMove + 1);\n        return selectedMove;\n      }\n    }\n\n    static int getManualMove(int player)\n    {\n      while (true)\n      {\n        Console.Write(\"{0}, enter you move (number): \", playerName(player));\n        ConsoleKeyInfo keyInfo = Console.ReadKey();\n        Console.WriteLine();  \n        if (keyInfo.Key == ConsoleKey.Escape)\n          return Unplayed;\n        if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)\n        {\n          int move = keyInfo.KeyChar - '1';  \n          if (GameBoard[move] == Unplayed)\n            return move;\n          else\n            Console.WriteLine(\"Spot {0} is already taken, please select again.\", move + 1);\n        }\n        else\n          Console.WriteLine(\"Illegal move, please select again.\\n\");\n      }\n    }\n\n    static int getRandomMove(int player)\n    {\n      int movesLeft = GameBoard.Count(position => position == Unplayed);\n      int x = rnd.Next(0, movesLeft);\n      for (int i = 0; i < GameBoard.Length; i++)  \n      {\n        if (GameBoard[i] == Unplayed && x < 0)    \n          return i;\n        x--;\n      }\n      return Unplayed;\n    }\n\n    \n    static int getSemiRandomMove(int player)\n    {\n      int posToPlay;\n      if (checkForWinningMove(player, out posToPlay))\n        return posToPlay;\n      if (checkForBlockingMove(player, out posToPlay))\n        return posToPlay;\n      return getRandomMove(player);\n    }\n\n    \n    static int getBestMove(int player)\n    {\n      return -1;\n    }\n\n    static bool checkForWinningMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(player, line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool checkForBlockingMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)\n    {\n      int cnt = 0;\n      posToPlay = int.MinValue;\n      foreach (int pos in line)\n      {\n        if (GameBoard[pos] == player)\n          cnt++;\n        else if (GameBoard[pos] == Unplayed)\n          posToPlay = pos;\n      }\n      return cnt == 2 && posToPlay >= 0;\n    }\n\n    static void playMove(int boardPosition, int player)\n    {\n      GameBoard[boardPosition] = player;\n    }\n\n    static bool isGameWon()\n    {\n      return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));\n    }\n\n    static bool takenBySamePlayer(int a, int b, int c)\n    {\n      return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];\n    }\n\n    static bool isGameTied()\n    {\n      return !GameBoard.Any(spot => spot == Unplayed);\n    }\n\n    \n    static Random rnd = new Random();\n\n    static void initializeGameBoard()\n    {\n      for (int i = 0; i < GameBoard.Length; i++)\n        GameBoard[i] = Unplayed;\n    }\n\n    static string playerName(int player)\n    {\n      return Players[player][0];\n    }\n\n    static string playerToken(int player)\n    {\n      return Players[player][1];\n    }\n\n    static int getNextPlayer(int player)\n    {\n      return (player + 1) % 2;\n    }\n\n    static void displayGameBoard()\n    {\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(0), pieceAt(1), pieceAt(2));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(3), pieceAt(4), pieceAt(5));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(6), pieceAt(7), pieceAt(8));\n      Console.WriteLine();\n    }\n\n    static string pieceAt(int boardPosition)\n    {\n      if (GameBoard[boardPosition] == Unplayed)\n        return (boardPosition + 1).ToString();  \n      return playerToken(GameBoard[boardPosition]);\n    }\n\n    private static bool playAgain()\n    {\n      Console.WriteLine(\"\\nDo you want to play again?\");\n      return Console.ReadKey(false).Key == ConsoleKey.Y;\n    }\n  }\n\n}\n", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n"}
{"id": 41652, "name": "Integer sequence", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 41653, "name": "Integer sequence", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n"}
{"id": 41654, "name": "DNS query", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n"}
{"id": 41655, "name": "DNS query", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n"}
{"id": 41656, "name": "Seven-sided dice from five-sided dice", "C#": "using System;\n\npublic class SevenSidedDice\n{\n    Random random = new Random();\n\t\t\n        static void Main(string[] args)\n\t\t{\n\t\t\tSevenSidedDice sevenDice = new SevenSidedDice();\n\t\t\tConsole.WriteLine(\"Random number from 1 to 7: \"+ sevenDice.seven());\n            Console.Read();\n\t\t}\n\t\t\n\t\tint seven()\n\t\t{\n\t\t\tint v=21;\n\t\t\twhile(v>20)\n\t\t\t\tv=five()+five()*5-6;\n\t\t\treturn 1+v%7;\n\t\t}\n\t\t\n\t\tint five()\n\t\t{\n        return 1 + random.Next(5);\n\t\t}\n}\n", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n"}
{"id": 41657, "name": "Create a two-dimensional array at runtime", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n"}
{"id": 41658, "name": "Chinese remainder theorem", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n"}
{"id": 41659, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n"}
{"id": 41660, "name": "Dragon curve", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n"}
{"id": 41661, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n"}
{"id": 41662, "name": "Doubly-linked list_Element insertion", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n"}
{"id": 41663, "name": "Quickselect algorithm", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n"}
{"id": 41664, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n"}
{"id": 41665, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n"}
{"id": 41666, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n"}
{"id": 41667, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 41668, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n"}
{"id": 41669, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n"}
{"id": 41670, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 41671, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 41672, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n"}
{"id": 41673, "name": "LZW compression", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n"}
{"id": 41674, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 41675, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n"}
{"id": 41676, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 41677, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n"}
{"id": 41678, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 41679, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n"}
{"id": 41680, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n"}
{"id": 41681, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 41682, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 41683, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n"}
{"id": 41684, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n"}
{"id": 41685, "name": "Universal Turing machine", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 41686, "name": "Universal Turing machine", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n"}
{"id": 41687, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n"}
{"id": 41688, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 41689, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n"}
{"id": 41690, "name": "Dining philosophers", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n"}
{"id": 41691, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 41692, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n"}
{"id": 41693, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 41694, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 41695, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 41696, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 41697, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n"}
{"id": 41698, "name": "Spiral matrix", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n"}
{"id": 41699, "name": "Optional parameters", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n"}
{"id": 41700, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n"}
{"id": 41701, "name": "Faulhaber's triangle", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 41702, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 41703, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 41704, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n"}
{"id": 41705, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 41706, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n"}
{"id": 41707, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n"}
{"id": 41708, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 41709, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n"}
{"id": 41710, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 41711, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n"}
{"id": 41712, "name": "Primes - allocate descendants to their ancestors", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n"}
{"id": 41713, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 41714, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 41715, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n"}
{"id": 41716, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n"}
{"id": 41717, "name": "XML_Output", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n"}
{"id": 41718, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 41719, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n"}
{"id": 41720, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n"}
{"id": 41721, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n"}
{"id": 41722, "name": "Colour pinstripe_Display", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n"}
{"id": 41723, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n"}
{"id": 41724, "name": "Animate a pendulum", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n"}
{"id": 41725, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 41726, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n"}
{"id": 41727, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n"}
{"id": 41728, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "VB": "Option Base {0|1}\n"}
{"id": 41729, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n"}
{"id": 41730, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n"}
{"id": 41731, "name": "Euler method", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n"}
{"id": 41732, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n"}
{"id": 41733, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 41734, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n"}
{"id": 41735, "name": "JortSort", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n"}
{"id": 41736, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n"}
{"id": 41737, "name": "Combinations and permutations", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n"}
{"id": 41738, "name": "Sort numbers lexicographically", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n"}
{"id": 41739, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n"}
{"id": 41740, "name": "Sorting algorithms_Shell sort", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n"}
{"id": 41741, "name": "Doubly-linked list_Definition", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n"}
{"id": 41742, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n"}
{"id": 41743, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n"}
{"id": 41744, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n"}
{"id": 41745, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n"}
{"id": 41746, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 41747, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n"}
{"id": 41748, "name": "Tokenize a string with escaping", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n"}
{"id": 41749, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n"}
{"id": 41750, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n"}
{"id": 41751, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n"}
{"id": 41752, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n"}
{"id": 41753, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n"}
{"id": 41754, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n"}
{"id": 41755, "name": "Singly-linked list_Traversal", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n"}
{"id": 41756, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n"}
{"id": 41757, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n"}
{"id": 41758, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 41759, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n"}
{"id": 41760, "name": "String interpolation (included)", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n"}
{"id": 41761, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n"}
{"id": 41762, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n"}
{"id": 41763, "name": "Bitwise operations", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 41764, "name": "Dragon curve", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n"}
{"id": 41765, "name": "Read a file line by line", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 41766, "name": "Doubly-linked list_Element insertion", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n"}
{"id": 41767, "name": "Smarandache prime-digital sequence", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n"}
{"id": 41768, "name": "Quickselect algorithm", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n"}
{"id": 41769, "name": "Non-decimal radices_Convert", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 41770, "name": "Walk a directory_Recursively", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 41771, "name": "Main step of GOST 28147-89", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype sBox [8][16]byte\n\ntype gost struct {\n    k87, k65, k43, k21 [256]byte\n    enc                []byte\n}\n\nfunc newGost(s *sBox) *gost {\n    var g gost\n    for i := range g.k87 {\n        g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]\n        g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]\n        g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]\n        g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]\n    }\n    g.enc = make([]byte, 8)\n    return &g\n}\n\nfunc (g *gost) f(x uint32) uint32 {\n    x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |\n        uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])\n    return x<<11 | x>>(32-11)\n}\n\n\n\n\n\n\nvar cbrf = sBox{\n    {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},\n    {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},\n    {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},\n    {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},\n    {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},\n    {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},\n    {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},\n    {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},\n}\n\nfunc u32(b []byte) uint32 {\n    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc b4(u uint32, b []byte) {\n    b[0] = byte(u)\n    b[1] = byte(u >> 8)\n    b[2] = byte(u >> 16)\n    b[3] = byte(u >> 24)\n}\n\nfunc (g *gost) mainStep(input []byte, key []byte) {\n    key32 := u32(key)\n    input1 := u32(input[:4])\n    input2 := u32(input[4:])\n    b4(g.f(key32+input1)^input2, g.enc[:4])\n    copy(g.enc[4:], input[:4])\n}\n\nfunc main() {\n    input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}\n    key := []byte{0xF9, 0x04, 0xC1, 0xE2}\n\n    g := newGost(&cbrf)\n    g.mainStep(input, key)\n    for _, b := range g.enc {\n        fmt.Printf(\"[%02x]\", b)\n    }\n    fmt.Println()\n}\n"}
{"id": 41772, "name": "State name puzzle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n"}
{"id": 41773, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 41774, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 41775, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 41776, "name": "CSV to HTML translation", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 41777, "name": "Classes", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 41778, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 41779, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 41780, "name": "LZW compression", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n"}
{"id": 41781, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 41782, "name": "Hofstadter Figure-Figure sequences", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 41783, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 41784, "name": "Magic squares of odd order", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 41785, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 41786, "name": "Yellowstone sequence", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 41787, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 41788, "name": "Cut a rectangle", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 41789, "name": "Mertens function", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n"}
{"id": 41790, "name": "Order by pair comparisons", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n"}
{"id": 41791, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 41792, "name": "Benford's law", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 41793, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 41794, "name": "Nautical bell", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 41795, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 41796, "name": "Snake", "C": "\n\n\n\n\n\n\n\n\nchar nonblocking_getch();\nvoid positional_putch(int x, int y, char ch);\nvoid millisecond_sleep(int n);\nvoid init_screen();\nvoid update_screen();\nvoid close_screen();\n\n\n\n#ifdef __linux__\n#define _POSIX_C_SOURCE 200809L\n#include <time.h> \n#include <ncurses.h> \nchar nonblocking_getch() { return getch(); }\nvoid positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }\nvoid millisecond_sleep(int n) { \n\tstruct timespec t = { 0, n * 1000000 };\n\tnanosleep(&t, 0);\n\t\n}\nvoid update_screen() { refresh(); }\nvoid init_screen() {\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\tnodelay(stdscr, TRUE);\n}\nvoid close_screen() { endwin(); }\n#endif\n\n\n#ifdef _WIN32\n#error \"not implemented\"\n#endif\n\n\n#include <time.h> \n#include <stdlib.h> \n\n#define w 80\n#define h 40\n\nint board[w * h];\nint head;\nenum Dir { N, E, S, W } dir;\nint quit;\n\nenum State { SPACE=0, FOOD=1, BORDER=2 };\n\n\n\nvoid age() {\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tif(board[i] < 0)\n\t\t\t++board[i];\n}\n\n\nvoid plant() {\n\tint r;\n\tdo\n\t\tr = rand() % (w * h);\n\twhile(board[r] != SPACE);\n\tboard[r] = FOOD;\n}\n\n\nvoid start(void) {\n        int i;\n\tfor(i = 0; i < w; ++i)\n\t\tboard[i] = board[i + (h - 1) * w] = BORDER;\n\tfor(i = 0; i < h; ++i)\n\t\tboard[i * w] = board[i * w + w - 1] = BORDER;\n\thead = w * (h - 1 - h % 2) / 2; \n\tboard[head] = -5;\n\tdir = N;\n\tquit = 0;\n\tsrand(time(0));\n\tplant();\n}\n\nvoid step() {\n\tint len = board[head];\n\tswitch(dir) {\n\t\tcase N: head -= w; break;\n\t\tcase S: head += w; break;\n\t\tcase W: --head; break;\n\t\tcase E: ++head; break;\n\t}\n\tswitch(board[head]) {\n\t\tcase SPACE:\n\t\t\tboard[head] = len - 1; \n\t\t\tage();\n\t\t\tbreak;\n\t\tcase FOOD:\n\t\t\tboard[head] = len - 1;\n\t\t\tplant();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tquit = 1;\n\t}\n}\n\nvoid show() {\n\tconst char * symbol = \" @.\";\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tpositional_putch(i / w, i % w,\n\t\t\tboard[i] < 0 ? '#' : symbol[board[i]]);\n\tupdate_screen();\n}\n\nint main (int argc, char * argv[]) {\n\tinit_screen();\n\tstart();\n\tdo {\n\t\tshow();\n\t\tswitch(nonblocking_getch()) {\n\t\t\tcase 'i': dir = N; break;\n\t\t\tcase 'j': dir = W; break;\n\t\t\tcase 'k': dir = S; break;\n\t\t\tcase 'l': dir = E; break;\n\t\t\tcase 'q': quit = 1; break;\n\t\t}\n\t\tstep();\n\t\tmillisecond_sleep(100); \n\t\t\n\t}\n\twhile(!quit);\n\tmillisecond_sleep(999);\n\tclose_screen();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"time\"\n\n\ttermbox \"github.com/nsf/termbox-go\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano())\n\tscore, err := playSnake()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Final score:\", score)\n}\n\ntype snake struct {\n\tbody          []position \n\theading       direction\n\twidth, height int\n\tcells         []termbox.Cell\n}\n\ntype position struct {\n\tX int\n\tY int\n}\n\ntype direction int\n\nconst (\n\tNorth direction = iota\n\tEast\n\tSouth\n\tWest\n)\n\nfunc (p position) next(d direction) position {\n\tswitch d {\n\tcase North:\n\t\tp.Y--\n\tcase East:\n\t\tp.X++\n\tcase South:\n\t\tp.Y++\n\tcase West:\n\t\tp.X--\n\t}\n\treturn p\n}\n\nfunc playSnake() (int, error) {\n\terr := termbox.Init()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer termbox.Close()\n\n\ttermbox.Clear(fg, bg)\n\ttermbox.HideCursor()\n\ts := &snake{\n\t\t\n\t\t\n\t\tbody:  make([]position, 0, 32),\n\t\tcells: termbox.CellBuffer(),\n\t}\n\ts.width, s.height = termbox.Size()\n\ts.drawBorder()\n\ts.startSnake()\n\ts.placeFood()\n\ts.flush()\n\n\tmoveCh, errCh := s.startEventLoop()\n\tconst delay = 125 * time.Millisecond\n\tfor t := time.NewTimer(delay); ; t.Reset(delay) {\n\t\tvar move direction\n\t\tselect {\n\t\tcase err = <-errCh:\n\t\t\treturn len(s.body), err\n\t\tcase move = <-moveCh:\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C \n\t\t\t}\n\t\tcase <-t.C:\n\t\t\tmove = s.heading\n\t\t}\n\t\tif s.doMove(move) {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn len(s.body), err\n}\n\nfunc (s *snake) startEventLoop() (<-chan direction, <-chan error) {\n\tmoveCh := make(chan direction)\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(errCh)\n\t\tfor {\n\t\t\tswitch ev := termbox.PollEvent(); ev.Type {\n\t\t\tcase termbox.EventKey:\n\t\t\t\tswitch ev.Ch { \n\t\t\t\tcase 'w', 'W', 'k', 'K':\n\t\t\t\t\tmoveCh <- North\n\t\t\t\tcase 'a', 'A', 'h', 'H':\n\t\t\t\t\tmoveCh <- West\n\t\t\t\tcase 's', 'S', 'j', 'J':\n\t\t\t\t\tmoveCh <- South\n\t\t\t\tcase 'd', 'D', 'l', 'L':\n\t\t\t\t\tmoveCh <- East\n\t\t\t\tcase 0:\n\t\t\t\t\tswitch ev.Key { \n\t\t\t\t\tcase termbox.KeyArrowUp:\n\t\t\t\t\t\tmoveCh <- North\n\t\t\t\t\tcase termbox.KeyArrowDown:\n\t\t\t\t\t\tmoveCh <- South\n\t\t\t\t\tcase termbox.KeyArrowLeft:\n\t\t\t\t\t\tmoveCh <- West\n\t\t\t\t\tcase termbox.KeyArrowRight:\n\t\t\t\t\t\tmoveCh <- East\n\t\t\t\t\tcase termbox.KeyEsc: \n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase termbox.EventResize:\n\t\t\t\t\n\t\t\t\terrCh <- errors.New(\"terminal resizing unsupported\")\n\t\t\t\treturn\n\t\t\tcase termbox.EventError:\n\t\t\t\terrCh <- ev.Err\n\t\t\t\treturn\n\t\t\tcase termbox.EventInterrupt:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn moveCh, errCh\n}\n\nfunc (s *snake) flush() {\n\ttermbox.Flush()\n\ts.cells = termbox.CellBuffer()\n}\n\nfunc (s *snake) getCellRune(p position) rune {\n\ti := p.Y*s.width + p.X\n\treturn s.cells[i].Ch\n}\nfunc (s *snake) setCell(p position, c termbox.Cell) {\n\ti := p.Y*s.width + p.X\n\ts.cells[i] = c\n}\n\nfunc (s *snake) drawBorder() {\n\tfor x := 0; x < s.width; x++ {\n\t\ts.setCell(position{x, 0}, border)\n\t\ts.setCell(position{x, s.height - 1}, border)\n\t}\n\tfor y := 0; y < s.height-1; y++ {\n\t\ts.setCell(position{0, y}, border)\n\t\ts.setCell(position{s.width - 1, y}, border)\n\t}\n}\n\nfunc (s *snake) placeFood() {\n\tfor {\n\t\t\n\t\tx := rand.Intn(s.width-2) + 1\n\t\ty := rand.Intn(s.height-2) + 1\n\t\tfoodp := position{x, y}\n\t\tr := s.getCellRune(foodp)\n\t\tif r != ' ' {\n\t\t\tcontinue\n\t\t}\n\t\ts.setCell(foodp, food)\n\t\treturn\n\t}\n}\n\nfunc (s *snake) startSnake() {\n\t\n\tx := rand.Intn(s.width/2) + s.width/4\n\ty := rand.Intn(s.height/2) + s.height/4\n\thead := position{x, y}\n\ts.setCell(head, snakeHead)\n\ts.body = append(s.body[:0], head)\n\ts.heading = direction(rand.Intn(4))\n}\n\nfunc (s *snake) doMove(move direction) bool {\n\thead := s.body[len(s.body)-1]\n\ts.setCell(head, snakeBody)\n\thead = head.next(move)\n\ts.heading = move\n\ts.body = append(s.body, head)\n\tr := s.getCellRune(head)\n\ts.setCell(head, snakeHead)\n\tgameOver := false\n\tswitch r {\n\tcase food.Ch:\n\t\ts.placeFood()\n\tcase border.Ch, snakeBody.Ch:\n\t\tgameOver = true\n\t\tfallthrough\n\tcase empty.Ch:\n\t\ts.setCell(s.body[0], empty)\n\t\ts.body = s.body[1:]\n\tdefault:\n\t\tpanic(r)\n\t}\n\ts.flush()\n\treturn gameOver\n}\n\nconst (\n\tfg = termbox.ColorWhite\n\tbg = termbox.ColorBlack\n)\n\n\n\nvar (\n\tempty     = termbox.Cell{Ch: ' ', Bg: bg, Fg: fg}\n\tborder    = termbox.Cell{Ch: '+', Bg: bg, Fg: termbox.ColorBlue}\n\tsnakeBody = termbox.Cell{Ch: '#', Bg: bg, Fg: termbox.ColorGreen}\n\tsnakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold}\n\tfood      = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed}\n)\n"}
{"id": 41797, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 41798, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 41799, "name": "Legendre prime counting function", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n"}
{"id": 41800, "name": "Use another language to call a function", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n"}
{"id": 41801, "name": "Longest string challenge", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n"}
{"id": 41802, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 41803, "name": "Universal Turing machine", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 41804, "name": "Create a file", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 41805, "name": "Unprimeable numbers", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n"}
{"id": 41806, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 41807, "name": "Pascal's triangle_Puzzle", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 41808, "name": "Chernick's Carmichael numbers", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n"}
{"id": 41809, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 41810, "name": "Find if a point is within a triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 41811, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41812, "name": "Tau function", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41813, "name": "Create an object at a given address", "C": "#include <stdio.h>\n\nint main()\n{\n  int intspace;\n  int *address;\n\n  address = &intspace; \n  *address = 65535;\n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  \n  *((char*)address) = 0x00;\n  *((char*)address+1) = 0x00;\n  *((char*)address+2) = 0xff;\n  *((char*)address+3) = 0xff; \n  \n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  return 0;\n}\n", "Go": "package main\n\nimport(\n\t\"fmt\"\n\t\"unsafe\"\n\t\"reflect\"\n)\n\nfunc pointer() {\n\tfmt.Printf(\"Pointer:\\n\")\n\n\t\n\t\n\t\n\t\n\tvar i int\n\tp := &i\n\n\tfmt.Printf(\"Before:\\n\\t%v: %v, %v\\n\", p, *p, i)\n\n\t*p = 3\n\n\tfmt.Printf(\"After:\\n\\t%v: %v, %v\\n\", p, *p, i)\n}\n\nfunc slice() {\n\tfmt.Printf(\"Slice:\\n\")\n\n\tvar a [10]byte\n\n\t\n\t\n\t\n\t\n\t\n\tvar h reflect.SliceHeader\n\th.Data = uintptr(unsafe.Pointer(&a)) \n\th.Len = len(a)\n\th.Cap = len(a)\n\n\t\n\ts := *(*[]byte)(unsafe.Pointer(&h))\n\n\tfmt.Printf(\"Before:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n\n\t\n\t\n\tcopy(s, \"A string.\")\n\n\tfmt.Printf(\"After:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n}\n\nfunc main() {\n\tpointer()\n\tfmt.Println()\n\n\tslice()\n}\n"}
{"id": 41814, "name": "Sequence of primorial primes", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n"}
{"id": 41815, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 41816, "name": "Bioinformatics_base count", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 41817, "name": "Dining philosophers", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n"}
{"id": 41818, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 41819, "name": "Factorions", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 41820, "name": "Logistic curve fitting in epidemiology", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n"}
{"id": 41821, "name": "Sorting algorithms_Strand sort", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n"}
{"id": 41822, "name": "Additive primes", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n"}
{"id": 41823, "name": "Inverted syntax", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n"}
{"id": 41824, "name": "Inverted syntax", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n"}
{"id": 41825, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 41826, "name": "Perfect totient numbers", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 41827, "name": "Delegates", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 41828, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41829, "name": "Sum of divisors", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 41830, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 41831, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 41832, "name": "Enforced immutability", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n"}
{"id": 41833, "name": "Sutherland-Hodgman polygon clipping", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n"}
{"id": 41834, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 41835, "name": "Bacon cipher", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 41836, "name": "Spiral matrix", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n"}
{"id": 41837, "name": "Optional parameters", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n"}
{"id": 41838, "name": "Optional parameters", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n"}
{"id": 41839, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 41840, "name": "Voronoi diagram", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 41841, "name": "Call a foreign-language function", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 41842, "name": "Call a foreign-language function", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 41843, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 41844, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 41845, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 41846, "name": "Faulhaber's triangle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n"}
{"id": 41847, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 41848, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 41849, "name": "Word wheel", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n"}
{"id": 41850, "name": "Array concatenation", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 41851, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 41852, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 41853, "name": "Musical scale", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 41854, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 41855, "name": "Primes - allocate descendants to their ancestors", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n"}
{"id": 41856, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 41857, "name": "Cartesian product of two or more lists", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 41858, "name": "First-class functions", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 41859, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 41860, "name": "XML_Output", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n"}
{"id": 41861, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 41862, "name": "Plot coordinate pairs", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 41863, "name": "Regular expressions", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 41864, "name": "Guess the number_With feedback (player)", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n"}
{"id": 41865, "name": "Hash from two arrays", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 41866, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 41867, "name": "Bin given limits", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 41868, "name": "Fractal tree", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n"}
{"id": 41869, "name": "Colour pinstripe_Display", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n"}
{"id": 41870, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 41871, "name": "Doomsday rule", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 41872, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n"}
{"id": 41873, "name": "Animate a pendulum", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n"}
{"id": 41874, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 41875, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 41876, "name": "Create a file on magnetic tape", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n"}
{"id": 41877, "name": "Sorting algorithms_Heapsort", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 41878, "name": "Playing cards", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 41879, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 41880, "name": "Sierpinski carpet", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 41881, "name": "Sorting algorithms_Bogosort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 41882, "name": "Merge and aggregate datasets", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n"}
{"id": 41883, "name": "Euler method", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 41884, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 41885, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 41886, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 41887, "name": "JortSort", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n"}
{"id": 41888, "name": "Leap year", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 41889, "name": "Combinations and permutations", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n"}
{"id": 41890, "name": "Sort numbers lexicographically", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n"}
{"id": 41891, "name": "Number names", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 41892, "name": "Compare length of two strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 41893, "name": "Sorting algorithms_Shell sort", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 41894, "name": "Doubly-linked list_Definition", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n"}
{"id": 41895, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 41896, "name": "Permutation test", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n"}
{"id": 41897, "name": "Möbius function", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n"}
{"id": 41898, "name": "Increment a numerical string", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 41899, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 41900, "name": "Sorting algorithms_Permutation sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n"}
{"id": 41901, "name": "Averages_Arithmetic mean", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 41902, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 41903, "name": "Abbreviations, simple", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 41904, "name": "Entropy", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n"}
{"id": 41905, "name": "Tokenize a string with escaping", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n"}
{"id": 41906, "name": "Hello world_Text", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n"}
{"id": 41907, "name": "Sexy primes", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef unsigned char bool;\n\nvoid sieve(bool *c, int limit) {\n    int i, p = 3, p2;\n    \n    c[0] = TRUE;\n    c[1] = TRUE;\n    \n    for (;;) {\n        p2 = p * p;\n        if (p2 >= limit) {\n            break;\n        }\n        for (i = p2; i < limit; i += 2*p) {\n            c[i] = TRUE;\n        }\n        for (;;) {\n            p += 2;\n            if (!c[p]) {\n                break;\n            }\n        }\n    }\n}\n\nvoid printHelper(const char *cat, int len, int lim, int n) {\n    const char *sp = strcmp(cat, \"unsexy primes\") ? \"sexy prime \" : \"\";\n    const char *verb = (len == 1) ? \"is\" : \"are\";\n    printf(\"Number of %s%s less than %'d = %'d\\n\", sp, cat, lim, len);\n    printf(\"The last %d %s:\\n\", n, verb);\n}\n\nvoid printArray(int *a, int len) {\n    int i;\n    printf(\"[\");\n    for (i = 0; i < len; ++i) printf(\"%d \", a[i]);\n    printf(\"\\b]\");\n}\n\nint main() {\n    int i, ix, n, lim = 1000035;\n    int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;\n    int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;\n    int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;\n    int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];\n    int last_un[10];\n    bool *sv = calloc(lim - 1, sizeof(bool)); \n    setlocale(LC_NUMERIC, \"\");\n    sieve(sv, lim);\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            unsexy++;\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pairs++;\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            trips++;\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            quads++;\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            quins++;\n        }\n    }\n    if (pairs < lpr) lpr = pairs;\n    if (trips < ltr) ltr = trips;\n    if (quads < lqd) lqd = quads;\n    if (quins < lqn) lqn = quins;\n    if (unsexy < lun) lun = unsexy;\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            un++;\n            if (un > unsexy - lun) {\n                last_un[un + lun - 1 - unsexy] = i;\n            }\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pr++;\n            if (pr > pairs - lpr) {\n                ix = pr + lpr - 1 - pairs;\n                last_pr[ix][0] = i; last_pr[ix][1] = i + 6;\n            }\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            tr++;\n            if (tr > trips - ltr) {\n                ix = tr + ltr - 1 - trips;\n                last_tr[ix][0] = i; last_tr[ix][1] = i + 6;\n                last_tr[ix][2] = i + 12;\n            }\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            qd++;\n            if (qd > quads - lqd) {\n                ix = qd + lqd - 1 - quads;\n                last_qd[ix][0] = i; last_qd[ix][1] = i + 6;\n                last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;\n            }\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            qn++;\n            if (qn > quins - lqn) {\n                ix = qn + lqn - 1 - quins;\n                last_qn[ix][0] = i; last_qn[ix][1] = i + 6;\n                last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;\n                last_qn[ix][4] = i + 24;\n            }\n        }\n    }\n\n    printHelper(\"pairs\", pairs, lim, lpr);\n    printf(\"  [\");\n    for (i = 0; i < lpr; ++i) {\n        printArray(last_pr[i], 2);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"triplets\", trips, lim, ltr);\n    printf(\"  [\");\n    for (i = 0; i < ltr; ++i) {\n        printArray(last_tr[i], 3);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quadruplets\", quads, lim, lqd);\n    printf(\"  [\");\n    for (i = 0; i < lqd; ++i) {\n        printArray(last_qd[i], 4);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quintuplets\", quins, lim, lqn);\n    printf(\"  [\");\n    for (i = 0; i < lqn; ++i) {\n        printArray(last_qn[i], 5);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"unsexy primes\", unsexy, lim, lun);\n    printf(\"  [\");\n    printArray(last_un, lun);\n    printf(\"\\b]\\n\");\n    free(sv);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n"}
{"id": 41908, "name": "Forward difference", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 41909, "name": "Primality by trial division", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 41910, "name": "Evaluate binomial coefficients", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 41911, "name": "Collections", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 41912, "name": "Singly-linked list_Traversal", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 41913, "name": "Bitmap_Write a PPM file", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 41914, "name": "Bitmap_Write a PPM file", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 41915, "name": "Delete a file", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 41916, "name": "Discordian date", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n"}
{"id": 41917, "name": "Flipping bits game", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 41918, "name": "Flipping bits game", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 41919, "name": "Hickerson series of almost integers", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 41920, "name": "Hickerson series of almost integers", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 41921, "name": "Hickerson series of almost integers", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 41922, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 41923, "name": "Average loop length", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 41924, "name": "String interpolation (included)", "C": "#include <stdio.h>\n\nint main() {\n  const char *extra = \"little\";\n  printf(\"Mary had a %s lamb.\\n\", extra);\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 41925, "name": "Sorting algorithms_Patience sort", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint* patienceSort(int* arr,int size){\n\tint decks[size][size],i,j,min,pickedRow;\n\t\n\tint *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){\n\t\t\t\tdecks[j][count[j]] = arr[i];\n\t\t\t\tcount[j]++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmin = decks[0][count[0]-1];\n\tpickedRow = 0;\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]>0 && decks[j][count[j]-1]<min){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t}\n\t\t}\n\t\tsortedArr[i] = min;\n\t\tcount[pickedRow]--;\n\t\t\n\t\tfor(j=0;j<size;j++)\n\t\t\tif(count[j]>0){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\t\n\tfree(count);\n\tfree(decks);\n\t\n\treturn sortedArr;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr, *sortedArr, i;\n\t\n\tif(argC==0)\n\t\tprintf(\"Usage : %s <integers to be sorted separated by space>\");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i<=argC;i++)\n\t\t\tarr[i-1] = atoi(argV[i]);\n\t\t\n\t\tsortedArr = patienceSort(arr,argC-1);\n\t\t\n\t\tfor(i=0;i<argC-1;i++)\n\t\t\tprintf(\"%d \",sortedArr[i]);\n\t}\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n"}
{"id": 41926, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 41927, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 41928, "name": "Bioinformatics_Sequence mutation", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 41929, "name": "Tau number", "C": "#include <stdio.h>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    unsigned int p;\n\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int count = 0;\n    unsigned int n;\n\n    printf(\"The first %d tau numbers are:\\n\", limit);\n    for (n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            printf(\"%6d\", n);\n            ++count;\n            if (count % 10 == 0) {\n                printf(\"\\n\");\n            }\n        }\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n"}
{"id": 41930, "name": "Determinant and permanent", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 41931, "name": "Determinant and permanent", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 41932, "name": "Partition function P", "C": "#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <gmp.h>\n\nmpz_t* partition(uint64_t n) {\n\tmpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));\n\tmpz_init_set_ui(pn[0], 1);\n\tmpz_init_set_ui(pn[1], 1);\n\tfor (uint64_t i = 2; i < n + 2; i ++) {\n\t\tmpz_init(pn[i]);\n\t\tfor (uint64_t k = 1, penta; ; k++) {\n\t\t\tpenta = k * (3 * k - 1) >> 1;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t\tpenta += k;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t}\n\t}\n\tmpz_t *tmp = &pn[n + 1];\n\tfor (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);\n\tfree(pn);\n\treturn tmp;\n}\n\nint main(int argc, char const *argv[]) {\n\tclock_t start = clock();\n\tmpz_t *p = partition(6666);\n\tgmp_printf(\"%Zd\\n\", p);\n\tprintf(\"Elapsed time: %.04f seconds\\n\",\n\t\t(double)(clock() - start) / (double)CLOCKS_PER_SEC);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n"}
{"id": 41933, "name": "Wireworld", "C": "\n#define ANIMATE_VT100_POSIX\n#include <stdio.h>\n#include <string.h>\n#ifdef ANIMATE_VT100_POSIX\n#include <time.h>\n#endif\n\nchar world_7x14[2][512] = {\n  {\n    \"+-----------+\\n\"\n    \"|tH.........|\\n\"\n    \"|.   .      |\\n\"\n    \"|   ...     |\\n\"\n    \"|.   .      |\\n\"\n    \"|Ht.. ......|\\n\"\n    \"+-----------+\\n\"\n  }\n};\n\nvoid next_world(const char *in, char *out, int w, int h)\n{\n  int i;\n\n  for (i = 0; i < w*h; i++) {\n    switch (in[i]) {\n    case ' ': out[i] = ' '; break;\n    case 't': out[i] = '.'; break;\n    case 'H': out[i] = 't'; break;\n    case '.': {\n      int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') +\n               (in[i-1]   == 'H')                    + (in[i+1]   == 'H') +\n               (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H');\n      out[i] = (hc == 1 || hc == 2) ? 'H' : '.';\n      break;\n    }\n    default:\n      out[i] = in[i];\n    }\n  }\n  out[i] = in[i];\n}\n\nint main()\n{\n  int f;\n\n  for (f = 0; ; f = 1 - f) {\n    puts(world_7x14[f]);\n    next_world(world_7x14[f], world_7x14[1-f], 14, 7);\n#ifdef ANIMATE_VT100_POSIX\n    printf(\"\\x1b[%dA\", 8);\n    printf(\"\\x1b[%dD\", 14);\n    {\n      static const struct timespec ts = { 0, 100000000 };\n      nanosleep(&ts, 0);\n    }\n#endif\n  }\n\n  return 0;\n}\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n"}
{"id": 41934, "name": "Ray-casting algorithm", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec;\ntypedef struct { int n; vec* v; } polygon_t, *polygon;\n\n#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}\n#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }\nBIN_V(sub, a.x - b.x, a.y - b.y);\nBIN_V(add, a.x + b.x, a.y + b.y);\nBIN_S(dot, a.x * b.x + a.y * b.y);\nBIN_S(cross, a.x * b.y - a.y * b.x);\n\n\nvec vmadd(vec a, double s, vec b)\n{\n\tvec c;\n\tc.x = a.x + s * b.x;\n\tc.y = a.y + s * b.y;\n\treturn c;\n}\n\n\nint intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)\n{\n\tvec dx = vsub(x1, x0), dy = vsub(y1, y0);\n\tdouble d = vcross(dy, dx), a;\n\tif (!d) return 0; \n\n\ta = (vcross(x0, dx) - vcross(y0, dx)) / d;\n\tif (sect)\n\t\t*sect = vmadd(y0, a, dy);\n\n\tif (a < -tol || a > 1 + tol) return -1;\n\tif (a < tol || a > 1 - tol) return 0;\n\n\ta = (vcross(x0, dy) - vcross(y0, dy)) / d;\n\tif (a < 0 || a > 1) return -1;\n\n\treturn 1;\n}\n\n\ndouble dist(vec x, vec y0, vec y1, double tol)\n{\n\tvec dy = vsub(y1, y0);\n\tvec x1, s;\n\tint r;\n\n\tx1.x = x.x + dy.y; x1.y = x.y - dy.x;\n\tr = intersect(x, x1, y0, y1, tol, &s);\n\tif (r == -1) return HUGE_VAL;\n\ts = vsub(s, x);\n\treturn sqrt(vdot(s, s));\n}\n\n#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)\n\nint inside(vec v, polygon p, double tol)\n{\n\t\n\tint i, k, crosses, intersectResult;\n\tvec *pv;\n\tdouble min_x, max_x, min_y, max_y;\n\n\tfor (i = 0; i < p->n; i++) {\n\t\tk = (i + 1) % p->n;\n\t\tmin_x = dist(v, p->v[i], p->v[k], tol);\n\t\tif (min_x < tol) return 0;\n\t}\n\n\tmin_x = max_x = p->v[0].x;\n\tmin_y = max_y = p->v[1].y;\n\n\t\n\tfor_v(i, pv, p) {\n\t\tif (pv->x > max_x) max_x = pv->x;\n\t\tif (pv->x < min_x) min_x = pv->x;\n\t\tif (pv->y > max_y) max_y = pv->y;\n\t\tif (pv->y < min_y) min_y = pv->y;\n\t}\n\tif (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)\n\t\treturn -1;\n\n\tmax_x -= min_x; max_x *= 2;\n\tmax_y -= min_y; max_y *= 2;\n\tmax_x += max_y;\n\n\tvec e;\n\twhile (1) {\n\t\tcrosses = 0;\n\t\t\n\t\te.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\t\te.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\n\t\tfor (i = 0; i < p->n; i++) {\n\t\t\tk = (i + 1) % p->n;\n\t\t\tintersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);\n\n\t\t\t\n\t\t\tif (!intersectResult) break;\n\n\t\t\tif (intersectResult == 1) crosses++;\n\t\t}\n\t\tif (i == p->n) break;\n\t}\n\treturn (crosses & 1) ? 1 : -1;\n}\n\nint main()\n{\n\tvec vsq[] = {\t{0,0}, {10,0}, {10,10}, {0,10},\n\t\t\t{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};\n\n\tpolygon_t sq = { 4, vsq }, \n\t\tsq_hole = { 8, vsq }; \n\n\tvec c = { 10, 5 }; \n\tvec d = { 5, 5 };\n\n\tprintf(\"%d\\n\", inside(c, &sq, 1e-10));\n\tprintf(\"%d\\n\", inside(c, &sq_hole, 1e-10));\n\n\tprintf(\"%d\\n\", inside(d, &sq, 1e-10));\t\n\tprintf(\"%d\\n\", inside(d, &sq_hole, 1e-10));  \n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 41935, "name": "Elliptic curve arithmetic", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 41936, "name": "Elliptic curve arithmetic", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 41937, "name": "Count occurrences of a substring", "C": "#include <stdio.h>\n#include <string.h>\n\nint match(const char *s, const char *p, int overlap)\n{\n        int c = 0, l = strlen(p);\n\n        while (*s != '\\0') {\n                if (strncmp(s++, p, l)) continue;\n                if (!overlap) s += l - 1;\n                c++;\n        }\n        return c;\n}\n\nint main()\n{\n        printf(\"%d\\n\", match(\"the three truths\", \"th\", 0));\n        printf(\"overlap:%d\\n\", match(\"abababababa\", \"aba\", 1));\n        printf(\"not:    %d\\n\", match(\"abababababa\", \"aba\", 0));\n        return 0;\n}\n", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n"}
{"id": 41938, "name": "Numbers with prime digits whose sum is 13", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 41939, "name": "Numbers with prime digits whose sum is 13", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 41940, "name": "String comparison", "C": "\nif (strcmp(a,b)) action_on_equality();\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n"}
{"id": 41941, "name": "Take notes on the command line", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 41942, "name": "Take notes on the command line", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 41943, "name": "Thiele's interpolation formula", "C": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define N 32\n#define N2 (N * (N - 1) / 2)\n#define STEP .05\n\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\n\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\n\n\n\ndouble rho(double *x, double *y, double *r, int i, int n)\n{\n\tif (n < 0) return 0;\n\tif (!n) return y[i];\n\n\tint idx = (N - 1 - n) * (N - n) / 2 + i;\n\tif (r[idx] != r[idx]) \n\t\tr[idx] = (x[i] - x[i + n])\n\t\t\t/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n\t\t\t+ rho(x, y, r, i + 1, n - 2);\n\treturn r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, int n)\n{\n\tif (n > N - 1) return 1;\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n\t\t+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\n#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)\n#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)\n#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\txval[i] = i * STEP;\n\t\tt_sin[i] = sin(xval[i]);\n\t\tt_cos[i] = cos(xval[i]);\n\t\tt_tan[i] = t_sin[i] / t_cos[i];\n\t}\n\tfor (i = 0; i < N2; i++)\n\t\t\n\t\tr_sin[i] = r_cos[i] = r_tan[i] = 0/0.;\n\n\tprintf(\"%16.14f\\n\", 6 * i_sin(.5));\n\tprintf(\"%16.14f\\n\", 3 * i_cos(.5));\n\tprintf(\"%16.14f\\n\", 4 * i_tan(1.));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n"}
{"id": 41944, "name": "Thiele's interpolation formula", "C": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define N 32\n#define N2 (N * (N - 1) / 2)\n#define STEP .05\n\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\n\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\n\n\n\ndouble rho(double *x, double *y, double *r, int i, int n)\n{\n\tif (n < 0) return 0;\n\tif (!n) return y[i];\n\n\tint idx = (N - 1 - n) * (N - n) / 2 + i;\n\tif (r[idx] != r[idx]) \n\t\tr[idx] = (x[i] - x[i + n])\n\t\t\t/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n\t\t\t+ rho(x, y, r, i + 1, n - 2);\n\treturn r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, int n)\n{\n\tif (n > N - 1) return 1;\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n\t\t+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\n#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)\n#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)\n#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\txval[i] = i * STEP;\n\t\tt_sin[i] = sin(xval[i]);\n\t\tt_cos[i] = cos(xval[i]);\n\t\tt_tan[i] = t_sin[i] / t_cos[i];\n\t}\n\tfor (i = 0; i < N2; i++)\n\t\t\n\t\tr_sin[i] = r_cos[i] = r_tan[i] = 0/0.;\n\n\tprintf(\"%16.14f\\n\", 6 * i_sin(.5));\n\tprintf(\"%16.14f\\n\", 3 * i_cos(.5));\n\tprintf(\"%16.14f\\n\", 4 * i_tan(1.));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n"}
{"id": 41945, "name": "Fibonacci word", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 41946, "name": "Fibonacci word", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 41947, "name": "Angles (geometric), normalization and conversion", "C": "#define PI 3.141592653589793\n#define TWO_PI 6.283185307179586\n\ndouble normalize2deg(double a) {\n  while (a < 0) a += 360;\n  while (a >= 360) a -= 360;\n  return a;\n}\ndouble normalize2grad(double a) {\n  while (a < 0) a += 400;\n  while (a >= 400) a -= 400;\n  return a;\n}\ndouble normalize2mil(double a) {\n  while (a < 0) a += 6400;\n  while (a >= 6400) a -= 6400;\n  return a;\n}\ndouble normalize2rad(double a) {\n  while (a < 0) a += TWO_PI;\n  while (a >= TWO_PI) a -= TWO_PI;\n  return a;\n}\n\ndouble deg2grad(double a) {return a * 10 / 9;}\ndouble deg2mil(double a) {return a * 160 / 9;}\ndouble deg2rad(double a) {return a * PI / 180;}\n\ndouble grad2deg(double a) {return a * 9 / 10;}\ndouble grad2mil(double a) {return a * 16;}\ndouble grad2rad(double a) {return a * PI / 200;}\n\ndouble mil2deg(double a) {return a * 9 / 160;}\ndouble mil2grad(double a) {return a / 16;}\ndouble mil2rad(double a) {return a * PI / 3200;}\n\ndouble rad2deg(double a) {return a * 180 / PI;}\ndouble rad2grad(double a) {return a * 200 / PI;}\ndouble rad2mil(double a) {return a * 3200 / PI;}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n"}
{"id": 41948, "name": "Find common directory path", "C": "#include <stdio.h>\n\nint common_len(const char *const *names, int n, char sep)\n{\n\tint i, pos;\n\tfor (pos = 0; ; pos++) {\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tif (names[i][pos] != '\\0' &&\n\t\t\t\t\tnames[i][pos] == names[0][pos])\n\t\t\t\tcontinue;\n\n\t\t\t\n\t\t\twhile (pos > 0 && names[0][--pos] != sep);\n\t\t\treturn pos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint main()\n{\n\tconst char *names[] = {\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t};\n\tint len = common_len(names, sizeof(names) / sizeof(const char*), '/');\n\n\tif (!len) printf(\"No common path\\n\");\n\telse      printf(\"Common path: %.*s\\n\", len, names[0]);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n"}
{"id": 41949, "name": "Verify distribution uniformity_Naive", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\ninline int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n\ninline int rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\n\nint check(int (*gen)(), int n, int cnt, double delta) \n{\n\tint i = cnt, *bins = calloc(sizeof(int), n);\n\tdouble ratio;\n\twhile (i--) bins[gen() - 1]++;\n\tfor (i = 0; i < n; i++) {\n\t\tratio = bins[i] * n / (double)cnt - 1;\n\t\tif (ratio > -delta && ratio < delta) continue;\n\n\t\tprintf(\"bin %d out of range: %d (%g%% vs %g%%), \",\n\t\t\ti + 1, bins[i], ratio * 100, delta * 100);\n\t\tbreak;\n\t}\n\tfree(bins);\n\treturn i == n;\n}\n\nint main()\n{\n\tint cnt = 1;\n\twhile ((cnt *= 10) <= 1000000) {\n\t\tprintf(\"Count = %d: \", cnt);\n\t\tprintf(check(rand5_7, 7, cnt, 0.03) ? \"flat\\n\" : \"NOT flat\\n\");\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 41950, "name": "Stirling numbers of the second kind", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 41951, "name": "Stirling numbers of the second kind", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 41952, "name": "Stirling numbers of the second kind", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 41953, "name": "Recaman's sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 41954, "name": "Recaman's sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 41955, "name": "Memory allocation", "C": "#include <stdlib.h>\n\n\n#define SIZEOF_MEMB (sizeof(int))\n#define NMEMB 100\n\nint main()\n{\n  int *ints = malloc(SIZEOF_MEMB*NMEMB);\n  \n  ints = realloc(ints, sizeof(int)*(NMEMB+1));\n  \n  int *int2 = calloc(NMEMB, SIZEOF_MEMB);\n  \n  free(ints); free(int2);\n  return 0;\n}\n", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n"}
{"id": 41956, "name": "Tic-tac-toe", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint b[3][3]; \n\nint check_winner()\n{\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tif (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])\n\t\t\treturn b[i][0];\n\t\tif (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])\n\t\t\treturn b[0][i];\n\t}\n\tif (!b[1][1]) return 0;\n\n\tif (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];\n\tif (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];\n\n\treturn 0;\n}\n\nvoid showboard()\n{\n\tconst char *t = \"X O\";\n\tint i, j;\n\tfor (i = 0; i < 3; i++, putchar('\\n'))\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%c \", t[ b[i][j] + 1 ]);\n\tprintf(\"-----\\n\");\n}\n\n#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)\nint best_i, best_j;\nint test_move(int val, int depth)\n{\n\tint i, j, score;\n\tint best = -1, changed = 0;\n\n\tif ((score = check_winner())) return (score == val) ? 1 : -1;\n\n\tfor_ij {\n\t\tif (b[i][j]) continue;\n\n\t\tchanged = b[i][j] = val;\n\t\tscore = -test_move(-val, depth + 1);\n\t\tb[i][j] = 0;\n\n\t\tif (score <= best) continue;\n\t\tif (!depth) {\n\t\t\tbest_i = i;\n\t\t\tbest_j = j;\n\t\t}\n\t\tbest = score;\n\t}\n\n\treturn changed ? best : 0;\n}\n\nconst char* game(int user)\n{\n\tint i, j, k, move, win = 0;\n\tfor_ij b[i][j] = 0;\n\n\tprintf(\"Board postions are numbered so:\\n1 2 3\\n4 5 6\\n7 8 9\\n\");\n\tprintf(\"You have O, I have X.\\n\\n\");\n\tfor (k = 0; k < 9; k++, user = !user) {\n\t\twhile(user) {\n\t\t\tprintf(\"your move: \");\n\t\t\tif (!scanf(\"%d\", &move)) {\n\t\t\t\tscanf(\"%*s\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (--move < 0 || move >= 9) continue;\n\t\t\tif (b[i = move / 3][j = move % 3]) continue;\n\n\t\t\tb[i][j] = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (!user) {\n\t\t\tif (!k) { \n\t\t\t\tbest_i = rand() % 3;\n\t\t\t\tbest_j = rand() % 3;\n\t\t\t} else\n\t\t\t\ttest_move(-1, 0);\n\n\t\t\tb[best_i][best_j] = -1;\n\t\t\tprintf(\"My move: %d\\n\", best_i * 3 + best_j + 1);\n\t\t}\n\n\t\tshowboard();\n\t\tif ((win = check_winner())) \n\t\t\treturn win == 1 ? \"You win.\\n\\n\": \"I win.\\n\\n\";\n\t}\n\treturn \"A draw.\\n\\n\";\n}\n\nint main()\n{\n\tint first = 0;\n\twhile (1) printf(\"%s\", game(first = !first));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n"}
{"id": 41957, "name": "Integer sequence", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 41958, "name": "Integer sequence", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 41959, "name": "Entropy_Narcissist", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n"}
{"id": 41960, "name": "Entropy_Narcissist", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n"}
{"id": 41961, "name": "DNS query", "C": "#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\t\t\n#include <stdio.h>\t\t\n#include <stdlib.h>\t\t\n#include <string.h>\t\t\n\nint\nmain()\n{\n\tstruct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n\t\n\tmemset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;     \n\thints.ai_socktype = SOCK_DGRAM;  \n\n\t\n\terror = getaddrinfo(\"www.kame.net\", NULL, &hints, &res0);\n\tif (error) {\n\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\texit(1);\n\t}\n\n\t\n\tfor (res = res0; res; res = res->ai_next) {\n\t\t\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\n\t\tif (error) {\n\t\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\\n\", host);\n\t\t}\n\t}\n\n\t\n\tfreeaddrinfo(res0);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 41962, "name": "Peano curve", "C": "\n\n#include <graphics.h>\n#include <math.h>\n\nvoid Peano(int x, int y, int lg, int i1, int i2) {\n\n\tif (lg == 1) {\n\t\tlineto(3*x,3*y);\n\t\treturn;\n\t}\n\t\n\tlg = lg/3;\n\tPeano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2);\n\tPeano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2);\n\tPeano(x+lg, y+lg, lg, i1, 1-i2);\n\tPeano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2);\n\tPeano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2);\n\tPeano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2);\n\tPeano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2);\n\tPeano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2);\n\tPeano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2);\n}\n\nint main(void) {\n\n\tinitwindow(1000,1000,\"Peano, Peano\");\n\n\tPeano(0, 0, 1000, 0, 0); \n\t\n\tgetch();\n\tcleardevice();\n\t\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar points []gg.Point\n\nconst width = 81\n\nfunc peano(x, y, lg, i1, i2 int) {\n    if lg == 1 {\n        px := float64(width-x) * 10\n        py := float64(width-y) * 10\n        points = append(points, gg.Point{px, py})\n        return\n    }\n    lg /= 3\n    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)\n    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)\n    peano(x+lg, y+lg, lg, i1, 1-i2)\n    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)\n    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)\n    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)\n    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)\n    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)\n    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)\n}\n\nfunc main() {\n    peano(0, 0, width, 0, 0)\n    dc := gg.NewContext(820, 820)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for _, p := range points {\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetRGB(1, 0, 1) \n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"peano.png\")\n}\n"}
{"id": 41963, "name": "Seven-sided dice from five-sided dice", "C": "int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n \nint rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\nint main()\n{\n\tprintf(check(rand5, 5, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\tprintf(check(rand7, 7, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 41964, "name": "Solve the no connection puzzle", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <math.h>\n\nint connections[15][2] = {\n    {0, 2}, {0, 3}, {0, 4}, \n    {1, 3}, {1, 4}, {1, 5}, \n    {6, 2}, {6, 3}, {6, 4}, \n    {7, 3}, {7, 4}, {7, 5}, \n    {2, 3}, {3, 4}, {4, 5}, \n};\n\nint pegs[8];\nint num = 0;\n\nbool valid() {\n    int i;\n    for (i = 0; i < 15; i++) {\n        if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid swap(int *a, int *b) {\n    int t = *a;\n    *a = *b;\n    *b = t;\n}\n\nvoid printSolution() {\n    printf(\"----- %d -----\\n\", num++);\n    printf(\"  %d %d\\n\",  pegs[0], pegs[1]);\n    printf(\"%d %d %d %d\\n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n    printf(\"  %d %d\\n\",  pegs[6], pegs[7]);\n    printf(\"\\n\");\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        int i;\n        for (i = le; i <= ri; i++) {\n            swap(pegs + le, pegs + i);\n            solution(le + 1, ri);\n            swap(pegs + le, pegs + i);\n        }\n    }\n}\n\nint main() {\n    int i;\n    for (i = 0; i < 8; i++) {\n        pegs[i] = i + 1;\n    }\n\n    solution(0, 8 - 1);\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n"}
{"id": 41965, "name": "Magnanimous numbers", "C": "#include <stdio.h> \n#include <string.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\n\nbool is_prime(ull n) {\n    ull d;\n    if (n < 2) return FALSE;\n    if (!(n % 2)) return n == 2;\n    if (!(n % 3)) return n == 3;\n    d = 5;\n    while (d * d <= n) {\n        if (!(n % d)) return FALSE;\n        d += 2;\n        if (!(n % d)) return FALSE;\n        d += 4;\n    }\n    return TRUE;\n}\n\nvoid ord(char *res, int n) {\n    char suffix[3];\n    int m = n % 100;\n    if (m >= 4 && m <= 20) {\n        sprintf(res,\"%dth\", n);\n        return;\n    }\n    switch(m % 10) {\n        case 1:\n            strcpy(suffix, \"st\");\n            break;\n        case 2:\n            strcpy(suffix, \"nd\");\n            break;\n        case 3:\n            strcpy(suffix, \"rd\");\n            break;\n        default:\n            strcpy(suffix, \"th\");\n            break;\n    }\n    sprintf(res, \"%d%s\", n, suffix);\n}\n\nbool is_magnanimous(ull n) {\n    ull p, q, r;\n    if (n < 10) return TRUE;\n    for (p = 10; ; p *= 10) {\n        q = n / p;\n        r = n % p;\n        if (!is_prime(q + r)) return FALSE;\n        if (q < 10) break;\n    }\n    return TRUE;\n}\n\nvoid list_mags(int from, int thru, int digs, int per_line) {\n    ull i = 0;\n    int c = 0;\n    char res1[13], res2[13];\n    if (from < 2) {\n        printf(\"\\nFirst %d magnanimous numbers:\\n\", thru);\n    } else {\n        ord(res1, from);\n        ord(res2, thru);\n        printf(\"\\n%s through %s magnanimous numbers:\\n\", res1, res2);\n    }\n    for ( ; c < thru; ++i) {\n        if (is_magnanimous(i)) {\n            if (++c >= from) {\n                printf(\"%*llu \", digs, i);\n                if (!(c % per_line)) printf(\"\\n\");\n            }\n        }\n    }\n}\n \nint main() {\n    list_mags(1, 45, 3, 15);\n    list_mags(241, 250, 1, 10);\n    list_mags(391, 400, 1, 10);\n    return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n"}
{"id": 41966, "name": "Extensible prime generator", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#define CHUNK_BYTES (32 << 8)\n#define CHUNK_SIZE (CHUNK_BYTES << 6)\n\nint field[CHUNK_BYTES];\n#define GET(x) (field[(x)>>6] &  1<<((x)>>1&31))\n#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))\n\ntypedef unsigned uint;\ntypedef struct {\n        uint *e;\n        uint cap, len;\n} uarray;\nuarray primes, offset;\n\nvoid push(uarray *a, uint n)\n{\n        if (a->len >= a->cap) {\n                if (!(a->cap *= 2)) a->cap = 16;\n                a->e = realloc(a->e, sizeof(uint) * a->cap);\n        }\n        a->e[a->len++] = n;\n}\n\nuint low;\nvoid init(void)\n{\n        uint p, q;\n\n        unsigned char f[1<<16];\n        memset(f, 0, sizeof(f));\n        push(&primes, 2);\n        push(&offset, 0);\n        for (p = 3; p < 1<<16; p += 2) {\n                if (f[p]) continue;\n                for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;\n                push(&primes, p);\n                push(&offset, q);\n        }\n        low = 1<<16;\n}\n\nvoid sieve(void)\n{\n        uint i, p, q, hi, ptop;\n        if (!low) init();\n\n        memset(field, 0, sizeof(field));\n\n        hi = low + CHUNK_SIZE;\n        ptop = sqrt(hi) * 2 + 1;\n\n        for (i = 1; (p = primes.e[i]*2) < ptop; i++) {\n                for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)\n                        SET(q);\n                offset.e[i] = q + low;\n        }\n\n        for (p = 1; p < CHUNK_SIZE; p += 2)\n                if (!GET(p)) push(&primes, low + p);\n\n        low = hi;\n}\n\nint main(void)\n{\n        uint i, p, c;\n\n        while (primes.len < 20) sieve();\n        printf(\"First 20:\");\n        for (i = 0; i < 20; i++)\n                printf(\" %u\", primes.e[i]);\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 150) sieve();\n        printf(\"Between 100 and 150:\");\n        for (i = 0; i < primes.len; i++) {\n                if ((p = primes.e[i]) >= 100 && p < 150)\n                        printf(\" %u\", primes.e[i]);\n        }\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 8000) sieve();\n        for (i = c = 0; i < primes.len; i++)\n                if ((p = primes.e[i]) >= 7700 && p < 8000) c++;\n        printf(\"%u primes between 7700 and 8000\\n\", c);\n\n        for (c = 10; c <= 100000000; c *= 10) {\n                while (primes.len < c) sieve();\n                printf(\"%uth prime: %u\\n\", c, primes.e[c-1]);\n        }\n\n        return 0;\n}\n", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"fmt\"\n)\n\nfunc main() {\n    p := newP()\n    fmt.Print(\"First twenty: \")\n    for i := 0; i < 20; i++ {\n        fmt.Print(p(), \" \")\n    }\n    fmt.Print(\"\\nBetween 100 and 150: \")\n    n := p()\n    for n <= 100 {\n        n = p()\n    }\n    for ; n < 150; n = p() {\n        fmt.Print(n, \" \")\n    }\n    for n <= 7700 {\n        n = p()\n    }\n    c := 0\n    for ; n < 8000; n = p() {\n        c++\n    }\n    fmt.Println(\"\\nNumber beween 7,700 and 8,000:\", c)\n    p = newP()\n    for i := 1; i < 10000; i++ {\n        p()\n    }\n    fmt.Println(\"10,000th prime:\", p())\n}\n\nfunc newP() func() int {\n    n := 1\n    var pq pQueue\n    top := &pMult{2, 4, 0}\n    return func() int {\n        for {\n            n++\n            if n < top.pMult { \n                heap.Push(&pq, &pMult{prime: n, pMult: n * n})\n                top = pq[0]\n                return n\n            }\n            \n            for top.pMult == n {\n                top.pMult += top.prime\n                heap.Fix(&pq, 0)\n                top = pq[0]\n            }\n        }\n    }\n}\n\ntype pMult struct {\n    prime int\n    pMult int\n    index int\n}\n\ntype pQueue []*pMult\n\nfunc (q pQueue) Len() int           { return len(q) }\nfunc (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }\nfunc (q pQueue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n    q[i].index = i\n    q[j].index = j\n}\nfunc (p *pQueue) Push(x interface{}) {\n    q := *p\n    e := x.(*pMult)\n    e.index = len(q)\n    *p = append(q, e)\n}\nfunc (p *pQueue) Pop() interface{} {\n    q := *p\n    last := len(q) - 1\n    e := q[last]\n    *p = q[:last]\n    return e\n}\n"}
{"id": 41967, "name": "Rock-paper-scissors", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define LEN 3 \n\n\nint rand_idx(double *p, int n)\n{\n\tdouble s = rand() / (RAND_MAX + 1.0);\n\tint i;\n\tfor (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);\n\treturn i;\n}\n\nint main()\n{\n\tint user_action, my_action;\n\tint user_rec[] = {0, 0, 0};\n\tconst char *names[] = { \"Rock\", \"Paper\", \"Scissors\" };\n\tchar str[2];\n\tconst char *winner[] = { \"We tied.\", \"Meself winned.\", \"You win.\" };\n\tdouble  p[LEN] = { 1./3, 1./3, 1./3 };\n \n\twhile (1) {\n\t\tmy_action = rand_idx(p,LEN);\n \n\t\tprintf(\"\\nYour choice [1-3]:\\n\"\n\t\t\t\"  1. Rock\\n  2. Paper\\n  3. Scissors\\n> \");\n \n\t\t\n\t\tif (!scanf(\"%d\", &user_action)) {\n\t\t\tscanf(\"%1s\", str);\n\t\t\tif (*str == 'q') {\n\t\t\t\tprintf(\"Your choices [rock : %d , paper :  %d , scissors %d] \",user_rec[0],user_rec[1], user_rec[2]); \n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tuser_action --;\n\t\tif (user_action > 2 || user_action < 0) {\n\t\t\tprintf(\"invalid choice; again\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tprintf(\"You chose %s; I chose %s. %s\\n\",\n\t\t\tnames[user_action], names[my_action],\n\t\t\twinner[(my_action - user_action + 3) % 3]);\n \n\t\tuser_rec[user_action]++;\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n"}
{"id": 41968, "name": "Rock-paper-scissors", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define LEN 3 \n\n\nint rand_idx(double *p, int n)\n{\n\tdouble s = rand() / (RAND_MAX + 1.0);\n\tint i;\n\tfor (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);\n\treturn i;\n}\n\nint main()\n{\n\tint user_action, my_action;\n\tint user_rec[] = {0, 0, 0};\n\tconst char *names[] = { \"Rock\", \"Paper\", \"Scissors\" };\n\tchar str[2];\n\tconst char *winner[] = { \"We tied.\", \"Meself winned.\", \"You win.\" };\n\tdouble  p[LEN] = { 1./3, 1./3, 1./3 };\n \n\twhile (1) {\n\t\tmy_action = rand_idx(p,LEN);\n \n\t\tprintf(\"\\nYour choice [1-3]:\\n\"\n\t\t\t\"  1. Rock\\n  2. Paper\\n  3. Scissors\\n> \");\n \n\t\t\n\t\tif (!scanf(\"%d\", &user_action)) {\n\t\t\tscanf(\"%1s\", str);\n\t\t\tif (*str == 'q') {\n\t\t\t\tprintf(\"Your choices [rock : %d , paper :  %d , scissors %d] \",user_rec[0],user_rec[1], user_rec[2]); \n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tuser_action --;\n\t\tif (user_action > 2 || user_action < 0) {\n\t\t\tprintf(\"invalid choice; again\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tprintf(\"You chose %s; I chose %s. %s\\n\",\n\t\t\tnames[user_action], names[my_action],\n\t\t\twinner[(my_action - user_action + 3) % 3]);\n \n\t\tuser_rec[user_action]++;\n\t}\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n"}
{"id": 41969, "name": "Create a two-dimensional array at runtime", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n   int user1 = 0, user2 = 0;\n   printf(\"Enter two integers.  Space delimited, please:  \");\n   scanf(\"%d %d\",&user1, &user2);\n   int array[user1][user2];\n   array[user1/2][user2/2] = user1 + user2;\n   printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n\n   return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n"}
{"id": 41970, "name": "Create a two-dimensional array at runtime", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n   int user1 = 0, user2 = 0;\n   printf(\"Enter two integers.  Space delimited, please:  \");\n   scanf(\"%d %d\",&user1, &user2);\n   int array[user1][user2];\n   array[user1/2][user2/2] = user1 + user2;\n   printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n\n   return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n"}
{"id": 41971, "name": "Chinese remainder theorem", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 41972, "name": "Chinese remainder theorem", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 41973, "name": "Vigenère cipher_Cryptanalysis", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *encoded =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\"\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\"\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\"\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\"\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\"\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\"\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\"\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\"\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\"\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\"\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\"\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\"\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\"\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\"\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\"\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\"\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n\nint best_match(const double *a, const double *b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n\n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n\n    return best_rotate;\n}\n\ndouble freq_every_nth(const int *msg, int len, int interval, char *key) {\n    double sum, d, ret;\n    double out[26], accu[26] = {0};\n    int i, j, rot;\n\n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n        key[j] = rot = best_match(out, freq);\n        key[j] += 'A';\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n\n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n\n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n\n    key[interval] = '\\0';\n    return ret;\n}\n\nint main() {\n    int txt[strlen(encoded)];\n    int len = 0, j;\n    char key[100];\n    double fit, best_fit = 1e100;\n\n    for (j = 0; encoded[j] != '\\0'; j++)\n        if (isupper(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n\n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        printf(\"%f, key length: %2d, %s\", fit, j, key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            printf(\" <--- best so far\");\n        }\n        printf(\"\\n\");\n    }\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar encoded = \n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [26]float64{\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n}\n\nfunc sum(a []float64) (sum float64) {\n    for _, f := range a {\n        sum += f\n    }\n    return\n}\n\nfunc bestMatch(a []float64) int {\n    sum := sum(a)\n    bestFit, bestRotate := 1e100, 0\n    for rotate := 0; rotate < 26; rotate++ {\n        fit := 0.0\n        for i := 0; i < 26; i++ {\n            d := a[(i+rotate)%26]/sum - freq[i]\n            fit += d * d / freq[i]\n        }\n        if fit < bestFit {\n            bestFit, bestRotate = fit, rotate\n        }\n    }\n    return bestRotate\n}\n\nfunc freqEveryNth(msg []int, key []byte) float64 {\n    l := len(msg)\n    interval := len(key)\n    out := make([]float64, 26)\n    accu := make([]float64, 26)\n    for j := 0; j < interval; j++ {\n        for k := 0; k < 26; k++ {\n            out[k] = 0.0\n        }\n        for i := j; i < l; i += interval {\n            out[msg[i]]++\n        }\n        rot := bestMatch(out)\n        key[j] = byte(rot + 65)\n        for i := 0; i < 26; i++ {\n            accu[i] += out[(i+rot)%26]\n        }\n    }\n    sum := sum(accu)\n    ret := 0.0\n    for i := 0; i < 26; i++ {\n        d := accu[i]/sum - freq[i]\n        ret += d * d / freq[i]\n    }\n    return ret\n}\n\nfunc decrypt(text, key string) string {\n    var sb strings.Builder\n    ki := 0\n    for _, c := range text {\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        ci := (c - rune(key[ki]) + 26) % 26\n        sb.WriteRune(ci + 65)\n        ki = (ki + 1) % len(key)\n    }\n    return sb.String()\n}\n\nfunc main() {\n    enc := strings.Replace(encoded, \" \", \"\", -1)\n    txt := make([]int, len(enc))\n    for i := 0; i < len(txt); i++ {\n        txt[i] = int(enc[i] - 'A')\n    }\n    bestFit, bestKey := 1e100, \"\"\n    fmt.Println(\"  Fit     Length   Key\")\n    for j := 1; j <= 26; j++ {\n        key := make([]byte, j)\n        fit := freqEveryNth(txt, key)\n        sKey := string(key)\n        fmt.Printf(\"%f    %2d     %s\", fit, j, sKey)\n        if fit < bestFit {\n            bestFit, bestKey = fit, sKey\n            fmt.Print(\" <--- best so far\")\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nBest key :\", bestKey)\n    fmt.Printf(\"\\nDecrypted text:\\n%s\\n\", decrypt(enc, bestKey))\n}\n"}
{"id": 41974, "name": "Pi", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\nmpz_t tmp1, tmp2, t5, t239, pows;\nvoid actan(mpz_t res, unsigned long base, mpz_t pows)\n{\n\tint i, neg = 1;\n\tmpz_tdiv_q_ui(res, pows, base);\n\tmpz_set(tmp1, res);\n\tfor (i = 3; ; i += 2) {\n\t\tmpz_tdiv_q_ui(tmp1, tmp1, base * base);\n\t\tmpz_tdiv_q_ui(tmp2, tmp1, i);\n\t\tif (mpz_cmp_ui(tmp2, 0) == 0) break;\n\t\tif (neg) mpz_sub(res, res, tmp2);\n\t\telse\t  mpz_add(res, res, tmp2);\n\t\tneg = !neg;\n\t}\n}\n\nchar * get_digits(int n, size_t* len)\n{\n\tmpz_ui_pow_ui(pows, 10, n + 20);\n\n\tactan(t5, 5, pows);\n\tmpz_mul_ui(t5, t5, 16);\n\n\tactan(t239, 239, pows);\n\tmpz_mul_ui(t239, t239, 4);\n\n\tmpz_sub(t5, t5, t239);\n\tmpz_ui_pow_ui(pows, 10, 20);\n\tmpz_tdiv_q(t5, t5, pows);\n\n\t*len = mpz_sizeinbase(t5, 10);\n\treturn mpz_get_str(0, 0, t5);\n}\n\nint main(int c, char **v)\n{\n\tunsigned long accu = 16384, done = 0;\n\tsize_t got;\n\tchar *s;\n\n\tmpz_init(tmp1);\n\tmpz_init(tmp2);\n\tmpz_init(t5);\n\tmpz_init(t239);\n\tmpz_init(pows);\n\n\twhile (1) {\n\t\ts = get_digits(accu, &got);\n\n\t\t\n\t\tgot -= 2; \n\t\twhile (s[got] == '0' || s[got] == '9') got--;\n\n\t\tprintf(\"%.*s\", (int)(got - done), s + done);\n\t\tfree(s);\n\n\t\tdone = got;\n\n\t\t\n\t\taccu *= 2;\n\t}\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n"}
{"id": 41975, "name": "Hofstadter Q sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n"}
{"id": 41976, "name": "Hofstadter Q sequence", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n"}
{"id": 41977, "name": "Y combinator", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct func_t *func;\ntypedef struct func_t {\n        func (*fn) (func, func);\n        func _;\n        int num;\n} func_t;\n\nfunc new(func(*f)(func, func), func _) {\n        func x = malloc(sizeof(func_t));\n        x->fn = f;\n        x->_ = _;       \n        x->num = 0;\n        return x;\n}\n\nfunc call(func f, func n) {\n        return f->fn(f, n);\n}\n\nfunc Y(func(*f)(func, func)) {\n        func g = new(f, 0);\n        g->_ = g;\n        return g;\n}\n\nfunc num(int n) {\n        func x = new(0, 0);\n        x->num = n;\n        return x;\n}\n\n\nfunc fac(func self, func n) {\n        int nn = n->num;\n        return nn > 1   ? num(nn * call(self->_, num(nn - 1))->num)\n                        : num(1);\n}\n\nfunc fib(func self, func n) {\n        int nn = n->num;\n        return nn > 1\n                ? num(  call(self->_, num(nn - 1))->num +\n                        call(self->_, num(nn - 2))->num )\n                : num(1);\n}\n\nvoid show(func n) { printf(\" %d\", n->num); }\n\nint main() {\n        int i;\n        func f = Y(fac);\n        printf(\"fac: \");\n        for (i = 1; i < 10; i++)\n                show( call(f, num(i)) );\n        printf(\"\\n\");\n\n        f = Y(fib);\n        printf(\"fib: \");\n        for (i = 1; i < 10; i++)\n                show( call(f, num(i)) );\n        printf(\"\\n\");\n\n        return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n"}
{"id": 41978, "name": "Return multiple values", "C": "#include<stdio.h>\n\ntypedef struct{\n\tint integer;\n\tfloat decimal;\n\tchar letter;\n\tchar string[100];\n\tdouble bigDecimal;\n}Composite;\n\nComposite example()\n{\n\tComposite C = {1, 2.3, 'a', \"Hello World\", 45.678};\n\treturn C;\n}\n\n\nint main()\n{\n\tComposite C = example();\n\n\tprintf(\"Values from a function returning a structure : { %d, %f, %c, %s, %f}\\n\", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);\n\n\treturn 0;\n}\n", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n"}
{"id": 41979, "name": "Van Eck sequence", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, const char *argv[]) {\n  const int max = 1000;\n  int *a = malloc(max * sizeof(int));\n  for (int n = 0; n < max - 1; n ++) {\n    for (int m = n - 1; m >= 0; m --) {\n      if (a[m] == a[n]) {\n        a[n+1] = n - m;\n        break;\n      }\n    }\n  }\n\n  printf(\"The first ten terms of the Van Eck sequence are:\\n\");\n  for (int i = 0; i < 10; i ++) printf(\"%d \", a[i]);\n  printf(\"\\n\\nTerms 991 to 1000 of the sequence are:\\n\");\n  for (int i = 990; i < 1000; i ++) printf(\"%d \", a[i]);\n  putchar('\\n');\n\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 41980, "name": "Van Eck sequence", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, const char *argv[]) {\n  const int max = 1000;\n  int *a = malloc(max * sizeof(int));\n  for (int n = 0; n < max - 1; n ++) {\n    for (int m = n - 1; m >= 0; m --) {\n      if (a[m] == a[n]) {\n        a[n+1] = n - m;\n        break;\n      }\n    }\n  }\n\n  printf(\"The first ten terms of the Van Eck sequence are:\\n\");\n  for (int i = 0; i < 10; i ++) printf(\"%d \", a[i]);\n  printf(\"\\n\\nTerms 991 to 1000 of the sequence are:\\n\");\n  for (int i = 990; i < 1000; i ++) printf(\"%d \", a[i]);\n  putchar('\\n');\n\n  return 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 41981, "name": "FTP", "C": "#include <ftplib.h>\n\nint main(void)\n{\n    netbuf *nbuf;\n\n    FtpInit();\n    FtpConnect(\"kernel.org\", &nbuf);\n    FtpLogin(\"anonymous\", \"\", nbuf);\n    FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);\n    FtpChdir(\"pub/linux/kernel\", nbuf);\n    FtpDir((void*)0, \".\", nbuf);\n    FtpGet(\"ftp.README\", \"README\", FTPLIB_ASCII, nbuf);\n    FtpQuit(nbuf);\n\n    return 0;\n}\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n"}
{"id": 41982, "name": "24 game", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <setjmp.h>\n#include <time.h>\n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom /= t;\n\t\tres->num /= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr/n/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); \n\t\tif (msg) {\n\t\t\t\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24.  Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good.  Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n"}
{"id": 41983, "name": "24 game", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <setjmp.h>\n#include <time.h>\n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom /= t;\n\t\tres->num /= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr/n/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); \n\t\tif (msg) {\n\t\t\t\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24.  Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good.  Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n"}
{"id": 41984, "name": "Loops_Continue", "C": "for(int i = 1;i <= 10; i++){\n   printf(\"%d\", i);\n   if(i % 5 == 0){\n      printf(\"\\n\");\n      continue;\n   }\n   printf(\", \");\n}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 10; i++ {\n        fmt.Printf(\"%d\", i)\n        if i%5 == 0 {\n            fmt.Printf(\"\\n\")\n            continue\n        }\n        fmt.Printf(\", \")\n    }\n}\n"}
{"id": 41985, "name": "Colour bars_Display", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 41986, "name": "Colour bars_Display", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 41987, "name": "Colour bars_Display", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 41988, "name": "Colour bars_Display", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 41989, "name": "LU decomposition", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define foreach(a, b, c) for (int a = b; a < c; a++)\n#define for_i foreach(i, 0, n)\n#define for_j foreach(j, 0, n)\n#define for_k foreach(k, 0, n)\n#define for_ij for_i for_j\n#define for_ijk for_ij for_k\n#define _dim int n\n#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }\n#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }\n\ntypedef double **mat;\n\n#define _zero(a) mat_zero(a, n)\nvoid mat_zero(mat x, int n) { for_ij x[i][j] = 0; }\n\n#define _new(a) a = mat_new(n)\nmat mat_new(_dim)\n{\n\tmat x = malloc(sizeof(double*) * n);\n\tx[0]  = malloc(sizeof(double) * n * n);\n\n\tfor_i x[i] = x[0] + n * i;\n\t_zero(x);\n\n\treturn x;\n}\n\n#define _copy(a) mat_copy(a, n)\nmat mat_copy(void *s, _dim)\n{\n\tmat x = mat_new(n);\n\tfor_ij x[i][j] = ((double (*)[n])s)[i][j];\n\treturn x;\n}\n\n#define _del(x) mat_del(x)\nvoid mat_del(mat x) { free(x[0]); free(x); }\n\n#define _QUOT(x) #x\n#define QUOTE(x) _QUOT(x)\n#define _show(a) printf(QUOTE(a)\" =\");mat_show(a, 0, n)\nvoid mat_show(mat x, char *fmt, _dim)\n{\n\tif (!fmt) fmt = \"%8.4g\";\n\tfor_i {\n\t\tprintf(i ? \"      \" : \" [ \");\n\t\tfor_j {\n\t\t\tprintf(fmt, x[i][j]);\n\t\t\tprintf(j < n - 1 ? \"  \" : i == n - 1 ? \" ]\\n\" : \"\\n\");\n\t\t}\n\t}\n}\n\n#define _mul(a, b) mat_mul(a, b, n)\nmat mat_mul(mat a, mat b, _dim)\n{\n\tmat c = _new(c);\n\tfor_ijk c[i][j] += a[i][k] * b[k][j];\n\treturn c;\n}\n\n#define _pivot(a, b) mat_pivot(a, b, n)\nvoid mat_pivot(mat a, mat p, _dim)\n{\n\tfor_ij { p[i][j] = (i == j); }\n\tfor_i  {\n\t\tint max_j = i;\n\t\tforeach(j, i, n)\n\t\t\tif (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;\n\n\t\tif (max_j != i)\n\t\t\tfor_k { _swap(p[i][k], p[max_j][k]); }\n\t}\n}\n\n#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)\nvoid mat_LU(mat A, mat L, mat U, mat P, _dim)\n{\n\t_zero(L); _zero(U);\n\t_pivot(A, P);\n\n\tmat Aprime = _mul(P, A);\n\n\tfor_i  { L[i][i] = 1; }\n\tfor_ij {\n\t\tdouble s;\n\t\tif (j <= i) {\n\t\t\t_sum_k(0, j, L[j][k] * U[k][i], s)\n\t\t\tU[j][i] = Aprime[j][i] - s;\n\t\t}\n\t\tif (j >= i) {\n\t\t\t_sum_k(0, i, L[j][k] * U[k][i], s);\n\t\t\tL[j][i] = (Aprime[j][i] - s) / U[i][i];\n\t\t}\n\t}\n\n\t_del(Aprime);\n}\n\ndouble A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};\ndouble A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};\n\nint main()\n{\n\tint n = 3;\n\tmat A, L, P, U;\n\n\t_new(L); _new(P); _new(U);\n\tA = _copy(A3);\n\t_LU(A, L, U, P);\n\t_show(A); _show(L); _show(U); _show(P);\n\t_del(A);  _del(L);  _del(U);  _del(P);\n\n\tprintf(\"\\n\");\n\n\tn = 4;\n\n\t_new(L); _new(P); _new(U);\n\tA = _copy(A4);\n\t_LU(A, L, U, P);\n\t_show(A); _show(L); _show(U); _show(P);\n\t_del(A);  _del(L);  _del(U);  _del(P);\n\n\treturn 0;\n}\n", "Go": "package main\n\nimport \"fmt\"\n    \ntype matrix [][]float64\n\nfunc zero(n int) matrix {\n    r := make([][]float64, n)\n    a := make([]float64, n*n)\n    for i := range r {\n        r[i] = a[n*i : n*(i+1)]\n    } \n    return r \n}\n    \nfunc eye(n int) matrix {\n    r := zero(n)\n    for i := range r {\n        r[i][i] = 1\n    }\n    return r\n}   \n    \nfunc (m matrix) print(label string) {\n    if label > \"\" {\n        fmt.Printf(\"%s:\\n\", label)\n    }\n    for _, r := range m {\n        for _, e := range r {\n            fmt.Printf(\" %9.5f\", e)\n        }\n        fmt.Println()\n    }\n}\n\nfunc (a matrix) pivotize() matrix { \n    p := eye(len(a))\n    for j, r := range a {\n        max := r[j] \n        row := j\n        for i := j; i < len(a); i++ {\n            if a[i][j] > max {\n                max = a[i][j]\n                row = i\n            }\n        }\n        if j != row {\n            \n            p[j], p[row] = p[row], p[j]\n        }\n    } \n    return p\n}\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    r := zero(len(m1))\n    for i, r1 := range m1 {\n        for j := range m2 {\n            for k := range m1 {\n                r[i][j] += r1[k] * m2[k][j]\n            }\n        }\n    }\n    return r\n}\n\nfunc (a matrix) lu() (l, u, p matrix) {\n    l = zero(len(a))\n    u = zero(len(a))\n    p = a.pivotize()\n    a = p.mul(a)\n    for j := range a {\n        l[j][j] = 1\n        for i := 0; i <= j; i++ {\n            sum := 0.\n            for k := 0; k < i; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            u[i][j] = a[i][j] - sum\n        }\n        for i := j; i < len(a); i++ {\n            sum := 0.\n            for k := 0; k < j; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            l[i][j] = (a[i][j] - sum) / u[j][j]\n        }\n    }\n    return\n}\n\nfunc main() {\n    showLU(matrix{\n        {1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}})\n    showLU(matrix{\n        {11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}})\n}\n\nfunc showLU(a matrix) {\n    a.print(\"\\na\")\n    l, u, p := a.lu()\n    l.print(\"l\")\n    u.print(\"u\") \n    p.print(\"p\") \n}\n"}
{"id": 41990, "name": "Bitwise operations", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n"}
{"id": 41991, "name": "Dragon curve", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n"}
{"id": 41992, "name": "Read a file line by line", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n"}
{"id": 41993, "name": "Doubly-linked list_Element insertion", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n"}
{"id": 41994, "name": "Smarandache prime-digital sequence", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n"}
{"id": 41995, "name": "Quickselect algorithm", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 41996, "name": "Non-decimal radices_Convert", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n"}
{"id": 41997, "name": "Walk a directory_Recursively", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n"}
{"id": 41998, "name": "Main step of GOST 28147-89", "C++": "UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)\n{\n    UINT_64 N;\n\tN = N1;\n\tN = (N<<32)|N2;\n\treturn UINT_64(N);\n}\n\nUINT_32 TGost::ReplaceBlock(UINT_32 x)\n{   \n    register i;\n    UINT_32 res = 0UL;\n    for(i=7;i>=0;i--)\n    {\n       ui4_0 = x>>(i*4);\n       ui4_0 = BS[ui4_0][i];\n       res = (res<<4)|ui4_0;\n    }\n    return res;\n}\n\nUINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)\n{\n   UINT_32 N1,N2,S=0UL;\n   N1=UINT_32(N);\n   N2=N>>32;\n   S = N1 + X % 0x4000000000000;\n   S = ReplaceBlock(S);\n   S = (S<<11)|(S>>21);\n   S ^= N2;\n   N2 = N1;\n   N1 = S;\n   return SWAP32(N2,N1);\n}\n", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n"}
{"id": 41999, "name": "State name puzzle", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n"}
{"id": 42000, "name": "CRC-32", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 42001, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 42002, "name": "CSV to HTML translation", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 42003, "name": "Classes", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n"}
{"id": 42004, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 42005, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 42006, "name": "LZW compression", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n"}
{"id": 42007, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 42008, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 42009, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 42010, "name": "Magic squares of odd order", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 42011, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 42012, "name": "Yellowstone sequence", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 42013, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 42014, "name": "Cut a rectangle", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 42015, "name": "Mertens function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n"}
{"id": 42016, "name": "Order by pair comparisons", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n"}
{"id": 42017, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42018, "name": "Benford's law", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42019, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 42020, "name": "Nautical bell", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 42021, "name": "Anonymous recursion", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 42022, "name": "Snake", "C++": "#include <windows.h>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nconst int WID = 60, HEI = 30, MAX_LEN = 600;\nenum DIR { NORTH, EAST, SOUTH, WEST };\n\nclass snake {\npublic:\n    snake() {\n        console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( \"Snake\" ); \n        COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );\n        SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );\n        CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );\n    }\n    void play() {\n        std::string a;\n        while( 1 ) {\n            createField(); alive = true;\n            while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }\n            COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );\n            SetConsoleTextAttribute( console, 0x000b );\n            std::cout << \"Play again [Y/N]? \"; std::cin >> a;\n            if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;\n        }\n    }\nprivate:\n    void createField() {\n        COORD coord = { 0, 0 }; DWORD c;\n        FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );\n        FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );\n        SetConsoleCursorPosition( console, coord );\n        int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;\n        for( x = 0; x < WID; x++ ) {\n            brd[x] = brd[x + WID * ( HEI - 1 )] = '+';\n        }\n        for( ; y < HEI; y++ ) {\n            brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';\n        }\n        do {\n            x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n        } while( brd[x + WID * y] );\n        brd[x + WID * y] = '@';\n        tailIdx = 0; headIdx = 4; x = 3; y = 2;\n        for( int c = tailIdx; c < headIdx; c++ ) {\n            brd[x + WID * y] = '#';\n            snk[c].X = 3 + c; snk[c].Y = 2;\n        }\n        head = snk[3]; dir = EAST; points = 0;\n    }\n    void readKey() {\n        if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;\n        if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;\n        if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;\n        if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;\n    }\n    void drawField() {\n        COORD coord; char t;\n        for( int y = 0; y < HEI; y++ ) {\n            coord.Y = y;\n            for( int x = 0; x < WID; x++ ) {\n                t = brd[x + WID * y]; if( !t ) continue;\n                coord.X = x; SetConsoleCursorPosition( console, coord );\n                if( coord.X == head.X && coord.Y == head.Y ) {\n                    SetConsoleTextAttribute( console, 0x002e );\n                    std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );\n                    continue;\n                }\n                switch( t ) {\n                    case '#': SetConsoleTextAttribute( console, 0x002a ); break;\n                    case '+': SetConsoleTextAttribute( console, 0x0019 ); break;\n                    case '@': SetConsoleTextAttribute( console, 0x004c ); break;\n                }\n                std::cout << t; SetConsoleTextAttribute( console, 0x0000 );\n            }\n        }\n        std::cout << t; SetConsoleTextAttribute( console, 0x0007 );\n        COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );\n        std::cout << \"Points: \" << points;\n    }\n    void moveSnake() {\n        switch( dir ) {\n            case NORTH: head.Y--; break;\n            case EAST: head.X++; break;\n            case SOUTH: head.Y++; break;\n            case WEST: head.X--; break;\n        }\n        char t = brd[head.X + WID * head.Y];\n        if( t && t != '@' ) { alive = false; return; }\n        brd[head.X + WID * head.Y] = '#';\n        snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;\n        if( ++headIdx >= MAX_LEN ) headIdx = 0;\n        if( t == '@' ) {\n            points++; int x, y;\n            do {\n                x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n            } while( brd[x + WID * y] );\n            brd[x + WID * y] = '@'; return;\n        }\n        SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';\n        brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;\n        if( ++tailIdx >= MAX_LEN ) tailIdx = 0;\n    }\n    bool alive; char brd[WID * HEI]; \n    HANDLE console; DIR dir; COORD snk[MAX_LEN];\n    COORD head; int tailIdx, headIdx, points;\n};\nint main( int argc, char* argv[] ) {\n    srand( static_cast<unsigned>( time( NULL ) ) );\n    snake s; s.play(); return 0;\n}\n", "C": "\n\n\n\n\n\n\n\n\nchar nonblocking_getch();\nvoid positional_putch(int x, int y, char ch);\nvoid millisecond_sleep(int n);\nvoid init_screen();\nvoid update_screen();\nvoid close_screen();\n\n\n\n#ifdef __linux__\n#define _POSIX_C_SOURCE 200809L\n#include <time.h> \n#include <ncurses.h> \nchar nonblocking_getch() { return getch(); }\nvoid positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }\nvoid millisecond_sleep(int n) { \n\tstruct timespec t = { 0, n * 1000000 };\n\tnanosleep(&t, 0);\n\t\n}\nvoid update_screen() { refresh(); }\nvoid init_screen() {\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\tnodelay(stdscr, TRUE);\n}\nvoid close_screen() { endwin(); }\n#endif\n\n\n#ifdef _WIN32\n#error \"not implemented\"\n#endif\n\n\n#include <time.h> \n#include <stdlib.h> \n\n#define w 80\n#define h 40\n\nint board[w * h];\nint head;\nenum Dir { N, E, S, W } dir;\nint quit;\n\nenum State { SPACE=0, FOOD=1, BORDER=2 };\n\n\n\nvoid age() {\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tif(board[i] < 0)\n\t\t\t++board[i];\n}\n\n\nvoid plant() {\n\tint r;\n\tdo\n\t\tr = rand() % (w * h);\n\twhile(board[r] != SPACE);\n\tboard[r] = FOOD;\n}\n\n\nvoid start(void) {\n        int i;\n\tfor(i = 0; i < w; ++i)\n\t\tboard[i] = board[i + (h - 1) * w] = BORDER;\n\tfor(i = 0; i < h; ++i)\n\t\tboard[i * w] = board[i * w + w - 1] = BORDER;\n\thead = w * (h - 1 - h % 2) / 2; \n\tboard[head] = -5;\n\tdir = N;\n\tquit = 0;\n\tsrand(time(0));\n\tplant();\n}\n\nvoid step() {\n\tint len = board[head];\n\tswitch(dir) {\n\t\tcase N: head -= w; break;\n\t\tcase S: head += w; break;\n\t\tcase W: --head; break;\n\t\tcase E: ++head; break;\n\t}\n\tswitch(board[head]) {\n\t\tcase SPACE:\n\t\t\tboard[head] = len - 1; \n\t\t\tage();\n\t\t\tbreak;\n\t\tcase FOOD:\n\t\t\tboard[head] = len - 1;\n\t\t\tplant();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tquit = 1;\n\t}\n}\n\nvoid show() {\n\tconst char * symbol = \" @.\";\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tpositional_putch(i / w, i % w,\n\t\t\tboard[i] < 0 ? '#' : symbol[board[i]]);\n\tupdate_screen();\n}\n\nint main (int argc, char * argv[]) {\n\tinit_screen();\n\tstart();\n\tdo {\n\t\tshow();\n\t\tswitch(nonblocking_getch()) {\n\t\t\tcase 'i': dir = N; break;\n\t\t\tcase 'j': dir = W; break;\n\t\t\tcase 'k': dir = S; break;\n\t\t\tcase 'l': dir = E; break;\n\t\t\tcase 'q': quit = 1; break;\n\t\t}\n\t\tstep();\n\t\tmillisecond_sleep(100); \n\t\t\n\t}\n\twhile(!quit);\n\tmillisecond_sleep(999);\n\tclose_screen();\n\treturn 0;\n}\n"}
{"id": 42023, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 42024, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 42025, "name": "Legendre prime counting function", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 42026, "name": "Use another language to call a function", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n"}
{"id": 42027, "name": "Longest string challenge", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n"}
{"id": 42028, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 42029, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 42030, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n"}
{"id": 42031, "name": "Unprimeable numbers", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n"}
{"id": 42032, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 42033, "name": "Pascal's triangle_Puzzle", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 42034, "name": "Chernick's Carmichael numbers", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 42035, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 42036, "name": "Find if a point is within a triangle", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 42037, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 42038, "name": "Tau function", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 42039, "name": "Create an object at a given address", "C++": "#include <string>\n#include <iostream>\n\nint main()\n{\n    \n    char* data = new char[sizeof(std::string)];\n\n    \n    std::string* stringPtr = new (data) std::string(\"ABCD\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    \n    stringPtr->~basic_string();\n    stringPtr = new (data) std::string(\"123456\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    stringPtr->~basic_string();\n    delete[] data;\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n  int intspace;\n  int *address;\n\n  address = &intspace; \n  *address = 65535;\n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  \n  *((char*)address) = 0x00;\n  *((char*)address+1) = 0x00;\n  *((char*)address+2) = 0xff;\n  *((char*)address+3) = 0xff; \n  \n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  return 0;\n}\n"}
{"id": 42040, "name": "Sequence of primorial primes", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n"}
{"id": 42041, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 42042, "name": "Bioinformatics_base count", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 42043, "name": "Dining philosophers", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n"}
{"id": 42044, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 42045, "name": "Factorions", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 42046, "name": "Logistic curve fitting in epidemiology", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n"}
{"id": 42047, "name": "Sorting algorithms_Strand sort", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n"}
{"id": 42048, "name": "Additive primes", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n"}
{"id": 42049, "name": "Inverted syntax", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n"}
{"id": 42050, "name": "Inverted syntax", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n"}
{"id": 42051, "name": "Inverted syntax", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n"}
{"id": 42052, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 42053, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 42054, "name": "Perfect totient numbers", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 42055, "name": "Delegates", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n"}
{"id": 42056, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 42057, "name": "Sum of divisors", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 42058, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42059, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42060, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42061, "name": "Enforced immutability", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n"}
{"id": 42062, "name": "Sutherland-Hodgman polygon clipping", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n"}
{"id": 42063, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 42064, "name": "Bacon cipher", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 42065, "name": "Spiral matrix", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 42066, "name": "Optional parameters", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n"}
{"id": 42067, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 42068, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 42069, "name": "Voronoi diagram", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 42070, "name": "Call a foreign-language function", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n"}
{"id": 42071, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 42072, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 42073, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 42074, "name": "Faulhaber's triangle", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n"}
{"id": 42075, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 42076, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 42077, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 42078, "name": "Word wheel", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n"}
{"id": 42079, "name": "Array concatenation", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n"}
{"id": 42080, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42081, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 42082, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 42083, "name": "Musical scale", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 42084, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 42085, "name": "Primes - allocate descendants to their ancestors", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n"}
{"id": 42086, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 42087, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 42088, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 42089, "name": "First-class functions", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n"}
{"id": 42090, "name": "Proper divisors", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 42091, "name": "XML_Output", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n"}
{"id": 42092, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 42093, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 42094, "name": "Plot coordinate pairs", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 42095, "name": "Regular expressions", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n"}
{"id": 42096, "name": "Guess the number_With feedback (player)", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n"}
{"id": 42097, "name": "Hash from two arrays", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n"}
{"id": 42098, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42099, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42100, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42101, "name": "Fractal tree", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n"}
{"id": 42102, "name": "Colour pinstripe_Display", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n"}
{"id": 42103, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 42104, "name": "Doomsday rule", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 42105, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n"}
{"id": 42106, "name": "Animate a pendulum", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 42107, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 42108, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 42109, "name": "Create a file on magnetic tape", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n"}
{"id": 42110, "name": "Sorting algorithms_Heapsort", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 42111, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n"}
{"id": 42112, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 42113, "name": "Sierpinski carpet", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 42114, "name": "Sorting algorithms_Bogosort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n"}
{"id": 42115, "name": "Merge and aggregate datasets", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n"}
{"id": 42116, "name": "Euler method", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n"}
{"id": 42117, "name": "Sequence of non-squares", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 42118, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42119, "name": "JortSort", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n"}
{"id": 42120, "name": "Leap year", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n"}
{"id": 42121, "name": "Combinations and permutations", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n"}
{"id": 42122, "name": "Sort numbers lexicographically", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n"}
{"id": 42123, "name": "Number names", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n"}
{"id": 42124, "name": "Compare length of two strings", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42125, "name": "Sorting algorithms_Shell sort", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 42126, "name": "Doubly-linked list_Definition", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n"}
{"id": 42127, "name": "Letter frequency", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 42128, "name": "Permutation test", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n"}
{"id": 42129, "name": "Möbius function", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n"}
{"id": 42130, "name": "Increment a numerical string", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n"}
{"id": 42131, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 42132, "name": "Sorting algorithms_Permutation sort", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n"}
{"id": 42133, "name": "Averages_Arithmetic mean", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 42134, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42135, "name": "Abbreviations, simple", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42136, "name": "Entropy", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 42137, "name": "Tokenize a string with escaping", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n"}
{"id": 42138, "name": "Hello world_Text", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n"}
{"id": 42139, "name": "Bitwise operations", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 42140, "name": "Read a file line by line", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 42141, "name": "Non-decimal radices_Convert", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 42142, "name": "Walk a directory_Recursively", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 42143, "name": "CRC-32", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 42144, "name": "Classes", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 42145, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42146, "name": "Kaprekar numbers", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42147, "name": "LZW compression", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 42148, "name": "Anonymous recursion", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 42149, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42150, "name": "Substring_Top and tail", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42151, "name": "Longest string challenge", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 42152, "name": "Create a file", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 42153, "name": "Sorting algorithms_Strand sort", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 42154, "name": "Delegates", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 42155, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42156, "name": "Abbreviations, easy", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42157, "name": "Enforced immutability", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 42158, "name": "Sutherland-Hodgman polygon clipping", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 42159, "name": "Call a foreign-language function", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 42160, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42161, "name": "Knuth's algorithm S", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42162, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42163, "name": "Command-line arguments", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42164, "name": "Array concatenation", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 42165, "name": "User input_Text", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 42166, "name": "Knapsack problem_0-1", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 42167, "name": "First-class functions", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 42168, "name": "Proper divisors", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 42169, "name": "Regular expressions", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 42170, "name": "Hash from two arrays", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 42171, "name": "Fractal tree", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 42172, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42173, "name": "Gray code", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42174, "name": "Playing cards", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 42175, "name": "Arrays", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 42176, "name": "Sierpinski carpet", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 42177, "name": "Sorting algorithms_Bogosort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 42178, "name": "Sequence of non-squares", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 42179, "name": "Substring", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 42180, "name": "Leap year", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 42181, "name": "Number names", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 42182, "name": "Compare length of two strings", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 42183, "name": "Sorting algorithms_Shell sort", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 42184, "name": "Letter frequency", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 42185, "name": "Increment a numerical string", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 42186, "name": "Strip a set of characters from a string", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 42187, "name": "Sorting algorithms_Permutation sort", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 42188, "name": "Averages_Arithmetic mean", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 42189, "name": "Entropy", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 42190, "name": "Bitwise operations", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 42191, "name": "Read a file line by line", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 42192, "name": "Non-decimal radices_Convert", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 42193, "name": "Walk a directory_Recursively", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 42194, "name": "CRC-32", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 42195, "name": "Classes", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 42196, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42197, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42198, "name": "LZW compression", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 42199, "name": "Anonymous recursion", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 42200, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42201, "name": "Substring_Top and tail", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42202, "name": "Longest string challenge", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 42203, "name": "Create a file", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 42204, "name": "Sorting algorithms_Strand sort", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 42205, "name": "Delegates", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 42206, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42207, "name": "Abbreviations, easy", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42208, "name": "Enforced immutability", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 42209, "name": "Sutherland-Hodgman polygon clipping", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 42210, "name": "Call a foreign-language function", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 42211, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42212, "name": "Knuth's algorithm S", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42213, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42214, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42215, "name": "Array concatenation", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 42216, "name": "User input_Text", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 42217, "name": "Knapsack problem_0-1", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 42218, "name": "First-class functions", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 42219, "name": "Proper divisors", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 42220, "name": "Regular expressions", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 42221, "name": "Hash from two arrays", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 42222, "name": "Fractal tree", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 42223, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42224, "name": "Gray code", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42225, "name": "Playing cards", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 42226, "name": "Arrays", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 42227, "name": "Sierpinski carpet", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 42228, "name": "Sorting algorithms_Bogosort", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 42229, "name": "Sequence of non-squares", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 42230, "name": "Substring", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 42231, "name": "Leap year", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 42232, "name": "Number names", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 42233, "name": "Compare length of two strings", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 42234, "name": "Sorting algorithms_Shell sort", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 42235, "name": "Letter frequency", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 42236, "name": "Increment a numerical string", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 42237, "name": "Strip a set of characters from a string", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 42238, "name": "Sorting algorithms_Permutation sort", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 42239, "name": "Averages_Arithmetic mean", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 42240, "name": "Entropy", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 42241, "name": "Hello world_Text", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n"}
{"id": 42242, "name": "Forward difference", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 42243, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 42244, "name": "Dragon curve", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n"}
{"id": 42245, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 42246, "name": "Doubly-linked list_Element insertion", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 42247, "name": "Smarandache prime-digital sequence", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n"}
{"id": 42248, "name": "Smarandache prime-digital sequence", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n"}
{"id": 42249, "name": "Quickselect algorithm", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 42250, "name": "Non-decimal radices_Convert", "Python": "i = int('1a',16)  \n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 42251, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 42252, "name": "State name puzzle", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n"}
{"id": 42253, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 42254, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 42255, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 42256, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 42257, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 42258, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 42259, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n"}
{"id": 42260, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 42261, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 42262, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 42263, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 42264, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 42265, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 42266, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 42267, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 42268, "name": "Mertens function", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n"}
{"id": 42269, "name": "Order by pair comparisons", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n"}
{"id": 42270, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 42271, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 42272, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 42273, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 42274, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 42275, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 42276, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 42277, "name": "Legendre prime counting function", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n"}
{"id": 42278, "name": "Use another language to call a function", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n"}
{"id": 42279, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 42280, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n"}
{"id": 42281, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n"}
{"id": 42282, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 42283, "name": "Unprimeable numbers", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 42284, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 42285, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 42286, "name": "Chernick's Carmichael numbers", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n"}
{"id": 42287, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 42288, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 42289, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 42290, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 42291, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 42292, "name": "Sequence of primorial primes", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n"}
{"id": 42293, "name": "Sequence of primorial primes", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n"}
{"id": 42294, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 42295, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 42296, "name": "Dining philosophers", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n"}
{"id": 42297, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 42298, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 42299, "name": "Logistic curve fitting in epidemiology", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n"}
{"id": 42300, "name": "Sorting algorithms_Strand sort", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n"}
{"id": 42301, "name": "Additive primes", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n"}
{"id": 42302, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 42303, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 42304, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n"}
{"id": 42305, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 42306, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 42307, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 42308, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 42309, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 42310, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n"}
{"id": 42311, "name": "Sutherland-Hodgman polygon clipping", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n"}
{"id": 42312, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 42313, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 42314, "name": "Spiral matrix", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n"}
{"id": 42315, "name": "Optional parameters", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n"}
{"id": 42316, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 42317, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 42318, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 42319, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 42320, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 42321, "name": "Faulhaber's triangle", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n"}
{"id": 42322, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 42323, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 42324, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 42325, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 42326, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 42327, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 42328, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 42329, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 42330, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 42331, "name": "Primes - allocate descendants to their ancestors", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n"}
{"id": 42332, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 42333, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 42334, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 42335, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n"}
{"id": 42336, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 42337, "name": "XML_Output", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n"}
{"id": 42338, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 42339, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 42340, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 42341, "name": "Guess the number_With feedback (player)", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n"}
{"id": 42342, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 42343, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 42344, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 42345, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 42346, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 42347, "name": "Fractal tree", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n"}
{"id": 42348, "name": "Colour pinstripe_Display", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 42349, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 42350, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 42351, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 42352, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n"}
{"id": 42353, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n"}
{"id": 42354, "name": "Animate a pendulum", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n"}
{"id": 42355, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 42356, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 42357, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 42358, "name": "Create a file on magnetic tape", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n"}
{"id": 42359, "name": "Sorting algorithms_Heapsort", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n"}
{"id": 42360, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 42361, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 42362, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 42363, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 42364, "name": "Euler method", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n"}
{"id": 42365, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 42366, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 42367, "name": "JortSort", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n"}
{"id": 42368, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 42369, "name": "Combinations and permutations", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n"}
{"id": 42370, "name": "Sort numbers lexicographically", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n"}
{"id": 42371, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 42372, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 42373, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 42374, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n"}
{"id": 42375, "name": "Doubly-linked list_Definition", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 42376, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 42377, "name": "Permutation test", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n"}
{"id": 42378, "name": "Möbius function", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n"}
{"id": 42379, "name": "Increment a numerical string", "Python": "next = str(int('123') + 1)\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 42380, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 42381, "name": "Sorting algorithms_Permutation sort", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n"}
{"id": 42382, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 42383, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 42384, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 42385, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n"}
{"id": 42386, "name": "Tokenize a string with escaping", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n"}
{"id": 42387, "name": "Hello world_Text", "Python": "print \"Hello world!\"\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 42388, "name": "Sexy primes", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 42389, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 42390, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 42391, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 42392, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 42393, "name": "Singly-linked list_Traversal", "Python": "for node in lst:\n    print node.value\n", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n"}
{"id": 42394, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 42395, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 42396, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 42397, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 42398, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 42399, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 42400, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 42401, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 42402, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 42403, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 42404, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 42405, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n"}
{"id": 42406, "name": "Sorting algorithms_Patience sort", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n"}
{"id": 42407, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 42408, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 42409, "name": "Tau number", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n"}
{"id": 42410, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 42411, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 42412, "name": "Partition function P", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n"}
{"id": 42413, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n"}
{"id": 42414, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n"}
{"id": 42415, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n"}
{"id": 42416, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n"}
{"id": 42417, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "Java": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) / subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n"}
{"id": 42418, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 42419, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 42420, "name": "String comparison", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n", "Java": "public class Compare\n{\n\t\n    \n    public static void compare (String A, String B)\n    {\n        if (A.equals(B))\n            System.debug(A + ' and  ' + B + ' are lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not lexically equal.');\n\n        if (A.equalsIgnoreCase(B))\n            System.debug(A + ' and  ' + B + ' are case-insensitive lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not case-insensitive lexically equal.');\n \n        if (A.compareTo(B) < 0)\n            System.debug(A + ' is lexically before ' + B);\n        else if (A.compareTo(B) > 0)\n            System.debug(A + ' is lexically after ' + B);\n \n        if (A.compareTo(B) >= 0)\n            System.debug(A + ' is not lexically before ' + B);\n        if (A.compareTo(B) <= 0)\n            System.debug(A + ' is not lexically after ' + B);\n \n        System.debug('The lexical relationship is: ' + A.compareTo(B));\n    }\n}\n"}
{"id": 42421, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n"}
{"id": 42422, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n"}
{"id": 42423, "name": "Thiele's interpolation formula", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n", "Java": "import static java.lang.Math.*;\n\npublic class Test {\n    final static int N = 32;\n    final static int N2 = (N * (N - 1) / 2);\n    final static double STEP = 0.05;\n\n    static double[] xval = new double[N];\n    static double[] t_sin = new double[N];\n    static double[] t_cos = new double[N];\n    static double[] t_tan = new double[N];\n\n    static double[] r_sin = new double[N2];\n    static double[] r_cos = new double[N2];\n    static double[] r_tan = new double[N2];\n\n    static double rho(double[] x, double[] y, double[] r, int i, int n) {\n        if (n < 0)\n            return 0;\n\n        if (n == 0)\n            return y[i];\n\n        int idx = (N - 1 - n) * (N - n) / 2 + i;\n        if (r[idx] != r[idx])\n            r[idx] = (x[i] - x[i + n])\n                    / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n                    + rho(x, y, r, i + 1, n - 2);\n\n        return r[idx];\n    }\n\n    static double thiele(double[] x, double[] y, double[] r, double xin, int n) {\n        if (n > N - 1)\n            return 1;\n        return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n                + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < N; i++) {\n            xval[i] = i * STEP;\n            t_sin[i] = sin(xval[i]);\n            t_cos[i] = cos(xval[i]);\n            t_tan[i] = t_sin[i] / t_cos[i];\n        }\n\n        for (int i = 0; i < N2; i++)\n            r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN;\n\n        System.out.printf(\"%16.14f%n\", 6 * thiele(t_sin, xval, r_sin, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 3 * thiele(t_cos, xval, r_cos, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 4 * thiele(t_tan, xval, r_tan, 1.0, 0));\n    }\n}\n"}
{"id": 42424, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n"}
{"id": 42425, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n"}
{"id": 42426, "name": "Angles (geometric), normalization and conversion", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n", "Java": "import java.text.DecimalFormat;\n\n\n\npublic class AnglesNormalizationAndConversion {\n\n    public static void main(String[] args) {\n        DecimalFormat formatAngle = new DecimalFormat(\"######0.000000\");\n        DecimalFormat formatConv = new DecimalFormat(\"###0.0000\");\n        System.out.printf(\"                               degrees    gradiens        mils     radians%n\");\n        for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {\n            for ( String units : new String[] {\"degrees\", \"gradiens\", \"mils\", \"radians\"}) {\n                double d = 0, g = 0, m = 0, r = 0;\n                switch (units) {\n                case \"degrees\":\n                    d = d2d(angle);\n                    g = d2g(d);\n                    m = d2m(d);\n                    r = d2r(d);\n                    break;\n                case \"gradiens\":\n                    g = g2g(angle);\n                    d = g2d(g);\n                    m = g2m(g);\n                    r = g2r(g);\n                    break;\n                case \"mils\":\n                    m = m2m(angle);\n                    d = m2d(m);\n                    g = m2g(m);\n                    r = m2r(m);\n                    break;\n                case \"radians\":\n                    r = r2r(angle);\n                    d = r2d(r);\n                    g = r2g(r);\n                    m = r2m(r);\n                    break;\n                }\n                System.out.printf(\"%15s  %8s = %10s  %10s  %10s  %10s%n\", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));\n            }\n        }\n    }\n\n    private static final double DEGREE = 360D;\n    private static final double GRADIAN = 400D;\n    private static final double MIL = 6400D;\n    private static final double RADIAN = (2 * Math.PI);\n    \n    private static double d2d(double a) {\n        return a % DEGREE;\n    }\n    private static double d2g(double a) {\n        return a * (GRADIAN / DEGREE);\n    }\n    private static double d2m(double a) {\n        return a * (MIL / DEGREE);\n    }\n    private static double d2r(double a) {\n        return a * (RADIAN / 360);\n    }\n\n    private static double g2d(double a) {\n        return a * (DEGREE / GRADIAN);\n    }\n    private static double g2g(double a) {\n        return a % GRADIAN;\n    }\n    private static double g2m(double a) {\n        return a * (MIL / GRADIAN);\n    }\n    private static double g2r(double a) {\n        return a * (RADIAN / GRADIAN);\n    }\n    \n    private static double m2d(double a) {\n        return a * (DEGREE / MIL);\n    }\n    private static double m2g(double a) {\n        return a * (GRADIAN / MIL);\n    }\n    private static double m2m(double a) {\n        return a % MIL;\n    }\n    private static double m2r(double a) {\n        return a * (RADIAN / MIL);\n    }\n    \n    private static double r2d(double a) {\n        return a * (DEGREE / RADIAN);\n    }\n    private static double r2g(double a) {\n        return a * (GRADIAN / RADIAN);\n    }\n    private static double r2m(double a) {\n        return a * (MIL / RADIAN);\n    }\n    private static double r2r(double a) {\n        return a % RADIAN;\n    }\n    \n}\n"}
{"id": 42427, "name": "Find common directory path", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n", "Java": "public class CommonPath {\n\tpublic static String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\tfor(int i = 0; i < paths.length; i++){\n\t\t\tfolders[i] = paths[i].split(\"/\"); \n\t\t}\n\t\tfor(int j = 0; j < folders[0].length; j++){\n\t\t\tString thisFolder = folders[0][j]; \n\t\t\tboolean allMatched = true; \n\t\t\tfor(int i = 1; i < folders.length && allMatched; i++){ \n\t\t\t\tif(folders[i].length < j){ \n\t\t\t\t\tallMatched = false; \n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tallMatched &= folders[i][j].equals(thisFolder); \n\t\t\t}\n\t\t\tif(allMatched){ \n\t\t\t\tcommonPath += thisFolder + \"/\"; \n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn commonPath;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString[] paths = { \"/home/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths));\n\t\t\n\t\tString[] paths2 = { \"/hame/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths2));\n\t}\n}\n"}
{"id": 42428, "name": "Verify distribution uniformity_Naive", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport java.util.function.IntSupplier;\n\npublic class Test {\n\n    static void distCheck(IntSupplier f, int nRepeats, double delta) {\n        Map<Integer, Integer> counts = new HashMap<>();\n\n        for (int i = 0; i < nRepeats; i++)\n            counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);\n\n        double target = nRepeats / (double) counts.size();\n        int deltaCount = (int) (delta / 100.0 * target);\n\n        counts.forEach((k, v) -> {\n            if (abs(target - v) >= deltaCount)\n                System.out.printf(\"distribution potentially skewed \"\n                        + \"for '%s': '%d'%n\", k, v);\n        });\n\n        counts.keySet().stream().sorted().forEach(k\n                -> System.out.printf(\"%d %d%n\", k, counts.get(k)));\n    }\n\n    public static void main(String[] a) {\n        distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);\n    }\n}\n"}
{"id": 42429, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n"}
{"id": 42430, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n"}
{"id": 42431, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n"}
{"id": 42432, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n"}
{"id": 42433, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n"}
{"id": 42434, "name": "Memory allocation", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n"}
{"id": 42435, "name": "Tic-tac-toe", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n", "Java": "import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Hashtable;\n\npublic class TicTacToe\n{\n\tpublic static void main(String[] args)\n\t{\n\t\tTicTacToe now=new TicTacToe();\n\t\tnow.startMatch();\n\t}\n\t\n\tprivate int[][] marks;\n\tprivate int[][] wins;\n\tprivate int[] weights;\n\tprivate char[][] grid;\n\tprivate final int knotcount=3;\n\tprivate final int crosscount=4;\n\tprivate final int totalcount=5;\n\tprivate final int playerid=0;\n\tprivate final int compid=1;\n\tprivate final int truceid=2;\n\tprivate final int playingid=3;\n\tprivate String movesPlayer;\n\tprivate byte override;\n\tprivate char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};\n\tprivate char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};\n\tprivate Hashtable<Integer,Integer> crossbank;\n\tprivate Hashtable<Integer,Integer> knotbank;\n\t\n\tpublic void startMatch()\n\t{\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tSystem.out.print(\"Start?(y/n):\");\n\t\tchar choice='y';\n\t\ttry\n\t\t{\n\t\t\tchoice=br.readLine().charAt(0);\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tSystem.out.println(e.getMessage());\n\t\t}\n\t\tif(choice=='n'||choice=='N')\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tSystem.out.println(\"Use a standard numpad as an entry grid, as so:\\n \");\n\t\tdisplay(numpad);\n\t\tSystem.out.println(\"Begin\");\n\t\tint playerscore=0;\n\t\tint compscore=0;\n\t\tdo\n\t\t{\n\t\t\tint result=startGame();\n\t\t\tif(result==playerid)\n\t\t\t\tplayerscore++;\n\t\t\telse if(result==compid)\n\t\t\t\tcompscore++;\n\t\t\tSystem.out.println(\"Score: Player-\"+playerscore+\" AI-\"+compscore);\n\t\t\tSystem.out.print(\"Another?(y/n):\");\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchoice=br.readLine().charAt(0);\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\t\n\t\t}while(choice!='n'||choice=='N');\n\t\t\n\t\tSystem.out.println(\"Game over.\");\n\t}\n\tprivate void put(int cell,int player)\n\t{\n\t\tint i=-1,j=-1;;\n\t\tswitch(cell)\n\t\t{\n\t\tcase 1:i=2;j=0;break;\n\t\tcase 2:i=2;j=1;break;\n\t\tcase 3:i=2;j=2;break;\n\t\tcase 4:i=1;j=0;break;\n\t\tcase 5:i=1;j=1;break;\n\t\tcase 6:i=1;j=2;break;\n\t\tcase 7:i=0;j=0;break;\n\t\tcase 8:i=0;j=1;break;\n\t\tcase 9:i=0;j=2;break;\n\t\tdefault:display(overridegrid);return;\n\t\t}\n\t\tchar mark='x';\n\t\tif(player==0)\n\t\t\tmark='o';\n\t\tgrid[i][j]=mark;\n\t\tdisplay(grid);\n\t}\n\tprivate int startGame()\n\t{\n\t\tinit();\n\t\tdisplay(grid);\n\t\tint status=playingid;\n\t\twhile(status==playingid)\n\t\t{\n\t\t\tput(playerMove(),0);\n\t\t\tif(override==1)\n\t\t\t{\n\t\t\t\tSystem.out.println(\"O wins.\");\n\t\t\t\treturn playerid;\n\t\t\t}\n\t\t\tstatus=checkForWin();\n\t\t\tif(status!=playingid)\n\t\t\t\tbreak;\n\t\t\ttry{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}\n\t\t\tput(compMove(),1);\n\t\t\tstatus=checkForWin();\n\t\t}\n\t\treturn status;\n\t}\n\tprivate void init()\n\t{\n\t\tmovesPlayer=\"\";\n\t\toverride=0;\n\t\tmarks=new int[8][6];\n\t\twins=new int[][]\t\n\t\t{\t\n\t\t\t\t{7,8,9},\n\t\t\t\t{4,5,6},\n\t\t\t\t{1,2,3},\n\t\t\t\t{7,4,1},\n\t\t\t\t{8,5,2},\n\t\t\t\t{9,6,3},\n\t\t\t\t{7,5,3},\n\t\t\t\t{9,5,1}\n\t\t};\n\t\tweights=new int[]{3,2,3,2,4,2,3,2,3};\n\t\tgrid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};\n\t\tcrossbank=new Hashtable<Integer,Integer>();\n\t\tknotbank=new Hashtable<Integer,Integer>();\n\t}\n\tprivate void mark(int m,int player)\n\t{\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t\tfor(int j=0;j<wins[i].length;j++)\n\t\t\t\tif(wins[i][j]==m)\n\t\t\t\t{\n\t\t\t\t\tmarks[i][j]=1;\n\t\t\t\t\tif(player==playerid)\n\t\t\t\t\t\tmarks[i][knotcount]++;\n\t\t\t\t\telse\n\t\t\t\t\t\tmarks[i][crosscount]++;\n\t\t\t\t\tmarks[i][totalcount]++;\n\t\t\t\t}\n\t}\n\tprivate void fixWeights()\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tif(marks[i][j]==1)\n\t\t\t\t\tif(weights[wins[i][j]-1]!=Integer.MIN_VALUE)\n\t\t\t\t\t\tweights[wins[i][j]-1]=Integer.MIN_VALUE;\n\t\t\n\t\tfor(int i=0;i<8;i++)\n\t\t{\n\t\t\tif(marks[i][totalcount]!=2)\n\t\t\t\tcontinue;\n\t\t\tif(marks[i][crosscount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=6;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(marks[i][knotcount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=5;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprivate int compMove()\n\t{\n\t\tint cell=move();\n\t\tSystem.out.println(\"Computer plays: \"+cell);\n\t\t\n\t\treturn cell;\n\t}\n\tprivate int move()\n\t{\n\t\tint max=Integer.MIN_VALUE;\n\t\tint cell=0;\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]>max)\n\t\t\t{\n\t\t\t\tmax=weights[i];\n\t\t\t\tcell=i+1;\n\t\t\t}\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tif(movesPlayer.equals(\"76\")||movesPlayer.equals(\"67\"))\n\t\t\tcell=9;\n\t\telse if(movesPlayer.equals(\"92\")||movesPlayer.equals(\"29\"))\n\t\t\tcell=3;\n\t\telse if (movesPlayer.equals(\"18\")||movesPlayer.equals(\"81\"))\n\t\t\tcell=7;\n\t\telse if(movesPlayer.equals(\"73\")||movesPlayer.equals(\"37\"))\n\t\t\tcell=4*((int)(Math.random()*2)+1);\n\t\telse if(movesPlayer.equals(\"19\")||movesPlayer.equals(\"91\"))\n\t\t\tcell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));\n\t\t\n\t\tmark(cell,1);\n\t\tfixWeights();\n\t\tcrossbank.put(cell, 0);\n\t\treturn cell;\n\t}\n\tprivate int playerMove()\n\t{\n\t\tSystem.out.print(\"What's your move?: \");\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tint cell=0;\n\t\tint okay=0;\n\t\twhile(okay==0)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcell=Integer.parseInt(br.readLine());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\tif(cell==7494)\n\t\t\t{\n\t\t\t\toverride=1;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)\n\t\t\t\tSystem.out.print(\"Invalid move. Try again:\");\n\t\t\telse\n\t\t\t\tokay=1;\n\t\t}\n\t\tplayerMoved(cell);\n\t\tSystem.out.println();\n\t\treturn cell;\n\t}\n\tprivate void playerMoved(int cell)\n\t{\n\t\tmovesPlayer+=cell;\n\t\tmark(cell,0);\n\t\tfixWeights();\n\t\tknotbank.put(cell, 0);\n\t}\n\tprivate int checkForWin()\n\t{\n\t\tint crossflag=0,knotflag=0;\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t{\n\t\t\tif(crossbank.containsKey(wins[i][0]))\n\t\t\t\tif(crossbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(crossbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcrossflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\tif(knotbank.containsKey(wins[i][0]))\n\t\t\t\tif(knotbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(knotbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tknotflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t}\n\t\tif(knotflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"O wins.\");\n\t\t\treturn playerid;\n\t\t}\n\t\telse if(crossflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"X wins.\");\n\t\t\treturn compid;\n\t\t}\n\t\t\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]!=Integer.MIN_VALUE)\n\t\t\t\treturn playingid;\n\t\tSystem.out.println(\"Truce\");\n\t\t\n\t\treturn truceid;\n\t}\n\tprivate void display(char[][] grid)\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t{\n\t\t\tSystem.out.println(\"\\n-------\");\n\t\t\tSystem.out.print(\"|\");\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tSystem.out.print(grid[i][j]+\"|\");\n\t\t}\n\t\tSystem.out.println(\"\\n-------\");\n\t}\n}\n"}
{"id": 42436, "name": "Tic-tac-toe", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n", "Java": "import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Hashtable;\n\npublic class TicTacToe\n{\n\tpublic static void main(String[] args)\n\t{\n\t\tTicTacToe now=new TicTacToe();\n\t\tnow.startMatch();\n\t}\n\t\n\tprivate int[][] marks;\n\tprivate int[][] wins;\n\tprivate int[] weights;\n\tprivate char[][] grid;\n\tprivate final int knotcount=3;\n\tprivate final int crosscount=4;\n\tprivate final int totalcount=5;\n\tprivate final int playerid=0;\n\tprivate final int compid=1;\n\tprivate final int truceid=2;\n\tprivate final int playingid=3;\n\tprivate String movesPlayer;\n\tprivate byte override;\n\tprivate char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};\n\tprivate char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};\n\tprivate Hashtable<Integer,Integer> crossbank;\n\tprivate Hashtable<Integer,Integer> knotbank;\n\t\n\tpublic void startMatch()\n\t{\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tSystem.out.print(\"Start?(y/n):\");\n\t\tchar choice='y';\n\t\ttry\n\t\t{\n\t\t\tchoice=br.readLine().charAt(0);\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tSystem.out.println(e.getMessage());\n\t\t}\n\t\tif(choice=='n'||choice=='N')\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tSystem.out.println(\"Use a standard numpad as an entry grid, as so:\\n \");\n\t\tdisplay(numpad);\n\t\tSystem.out.println(\"Begin\");\n\t\tint playerscore=0;\n\t\tint compscore=0;\n\t\tdo\n\t\t{\n\t\t\tint result=startGame();\n\t\t\tif(result==playerid)\n\t\t\t\tplayerscore++;\n\t\t\telse if(result==compid)\n\t\t\t\tcompscore++;\n\t\t\tSystem.out.println(\"Score: Player-\"+playerscore+\" AI-\"+compscore);\n\t\t\tSystem.out.print(\"Another?(y/n):\");\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchoice=br.readLine().charAt(0);\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\t\n\t\t}while(choice!='n'||choice=='N');\n\t\t\n\t\tSystem.out.println(\"Game over.\");\n\t}\n\tprivate void put(int cell,int player)\n\t{\n\t\tint i=-1,j=-1;;\n\t\tswitch(cell)\n\t\t{\n\t\tcase 1:i=2;j=0;break;\n\t\tcase 2:i=2;j=1;break;\n\t\tcase 3:i=2;j=2;break;\n\t\tcase 4:i=1;j=0;break;\n\t\tcase 5:i=1;j=1;break;\n\t\tcase 6:i=1;j=2;break;\n\t\tcase 7:i=0;j=0;break;\n\t\tcase 8:i=0;j=1;break;\n\t\tcase 9:i=0;j=2;break;\n\t\tdefault:display(overridegrid);return;\n\t\t}\n\t\tchar mark='x';\n\t\tif(player==0)\n\t\t\tmark='o';\n\t\tgrid[i][j]=mark;\n\t\tdisplay(grid);\n\t}\n\tprivate int startGame()\n\t{\n\t\tinit();\n\t\tdisplay(grid);\n\t\tint status=playingid;\n\t\twhile(status==playingid)\n\t\t{\n\t\t\tput(playerMove(),0);\n\t\t\tif(override==1)\n\t\t\t{\n\t\t\t\tSystem.out.println(\"O wins.\");\n\t\t\t\treturn playerid;\n\t\t\t}\n\t\t\tstatus=checkForWin();\n\t\t\tif(status!=playingid)\n\t\t\t\tbreak;\n\t\t\ttry{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}\n\t\t\tput(compMove(),1);\n\t\t\tstatus=checkForWin();\n\t\t}\n\t\treturn status;\n\t}\n\tprivate void init()\n\t{\n\t\tmovesPlayer=\"\";\n\t\toverride=0;\n\t\tmarks=new int[8][6];\n\t\twins=new int[][]\t\n\t\t{\t\n\t\t\t\t{7,8,9},\n\t\t\t\t{4,5,6},\n\t\t\t\t{1,2,3},\n\t\t\t\t{7,4,1},\n\t\t\t\t{8,5,2},\n\t\t\t\t{9,6,3},\n\t\t\t\t{7,5,3},\n\t\t\t\t{9,5,1}\n\t\t};\n\t\tweights=new int[]{3,2,3,2,4,2,3,2,3};\n\t\tgrid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};\n\t\tcrossbank=new Hashtable<Integer,Integer>();\n\t\tknotbank=new Hashtable<Integer,Integer>();\n\t}\n\tprivate void mark(int m,int player)\n\t{\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t\tfor(int j=0;j<wins[i].length;j++)\n\t\t\t\tif(wins[i][j]==m)\n\t\t\t\t{\n\t\t\t\t\tmarks[i][j]=1;\n\t\t\t\t\tif(player==playerid)\n\t\t\t\t\t\tmarks[i][knotcount]++;\n\t\t\t\t\telse\n\t\t\t\t\t\tmarks[i][crosscount]++;\n\t\t\t\t\tmarks[i][totalcount]++;\n\t\t\t\t}\n\t}\n\tprivate void fixWeights()\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tif(marks[i][j]==1)\n\t\t\t\t\tif(weights[wins[i][j]-1]!=Integer.MIN_VALUE)\n\t\t\t\t\t\tweights[wins[i][j]-1]=Integer.MIN_VALUE;\n\t\t\n\t\tfor(int i=0;i<8;i++)\n\t\t{\n\t\t\tif(marks[i][totalcount]!=2)\n\t\t\t\tcontinue;\n\t\t\tif(marks[i][crosscount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=6;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(marks[i][knotcount]==2)\n\t\t\t{\n\t\t\t\tint p=i,q=-1;\n\t\t\t\tif(marks[i][0]==0)\n\t\t\t\t\tq=0;\n\t\t\t\telse if(marks[i][1]==0)\n\t\t\t\t\tq=1;\n\t\t\t\telse if(marks[i][2]==0)\n\t\t\t\t\tq=2;\n\t\t\t\t\n\t\t\t\tif(weights[wins[p][q]-1]!=Integer.MIN_VALUE)\n\t\t\t\t{\n\t\t\t\t\tweights[wins[p][q]-1]=5;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprivate int compMove()\n\t{\n\t\tint cell=move();\n\t\tSystem.out.println(\"Computer plays: \"+cell);\n\t\t\n\t\treturn cell;\n\t}\n\tprivate int move()\n\t{\n\t\tint max=Integer.MIN_VALUE;\n\t\tint cell=0;\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]>max)\n\t\t\t{\n\t\t\t\tmax=weights[i];\n\t\t\t\tcell=i+1;\n\t\t\t}\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tif(movesPlayer.equals(\"76\")||movesPlayer.equals(\"67\"))\n\t\t\tcell=9;\n\t\telse if(movesPlayer.equals(\"92\")||movesPlayer.equals(\"29\"))\n\t\t\tcell=3;\n\t\telse if (movesPlayer.equals(\"18\")||movesPlayer.equals(\"81\"))\n\t\t\tcell=7;\n\t\telse if(movesPlayer.equals(\"73\")||movesPlayer.equals(\"37\"))\n\t\t\tcell=4*((int)(Math.random()*2)+1);\n\t\telse if(movesPlayer.equals(\"19\")||movesPlayer.equals(\"91\"))\n\t\t\tcell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));\n\t\t\n\t\tmark(cell,1);\n\t\tfixWeights();\n\t\tcrossbank.put(cell, 0);\n\t\treturn cell;\n\t}\n\tprivate int playerMove()\n\t{\n\t\tSystem.out.print(\"What's your move?: \");\n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tint cell=0;\n\t\tint okay=0;\n\t\twhile(okay==0)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcell=Integer.parseInt(br.readLine());\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tSystem.out.println(e.getMessage());\n\t\t\t}\n\t\t\tif(cell==7494)\n\t\t\t{\n\t\t\t\toverride=1;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)\n\t\t\t\tSystem.out.print(\"Invalid move. Try again:\");\n\t\t\telse\n\t\t\t\tokay=1;\n\t\t}\n\t\tplayerMoved(cell);\n\t\tSystem.out.println();\n\t\treturn cell;\n\t}\n\tprivate void playerMoved(int cell)\n\t{\n\t\tmovesPlayer+=cell;\n\t\tmark(cell,0);\n\t\tfixWeights();\n\t\tknotbank.put(cell, 0);\n\t}\n\tprivate int checkForWin()\n\t{\n\t\tint crossflag=0,knotflag=0;\n\t\tfor(int i=0;i<wins.length;i++)\n\t\t{\n\t\t\tif(crossbank.containsKey(wins[i][0]))\n\t\t\t\tif(crossbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(crossbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcrossflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\tif(knotbank.containsKey(wins[i][0]))\n\t\t\t\tif(knotbank.containsKey(wins[i][1]))\n\t\t\t\t\tif(knotbank.containsKey(wins[i][2]))\n\t\t\t\t\t{\n\t\t\t\t\t\tknotflag=1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t}\n\t\tif(knotflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"O wins.\");\n\t\t\treturn playerid;\n\t\t}\n\t\telse if(crossflag==1)\n\t\t{\n\t\t\tdisplay(grid);\n\t\t\tSystem.out.println(\"X wins.\");\n\t\t\treturn compid;\n\t\t}\n\t\t\n\t\tfor(int i=0;i<weights.length;i++)\n\t\t\tif(weights[i]!=Integer.MIN_VALUE)\n\t\t\t\treturn playingid;\n\t\tSystem.out.println(\"Truce\");\n\t\t\n\t\treturn truceid;\n\t}\n\tprivate void display(char[][] grid)\n\t{\n\t\tfor(int i=0;i<3;i++)\n\t\t{\n\t\t\tSystem.out.println(\"\\n-------\");\n\t\t\tSystem.out.print(\"|\");\n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t\tSystem.out.print(grid[i][j]+\"|\");\n\t\t}\n\t\tSystem.out.println(\"\\n-------\");\n\t}\n}\n"}
{"id": 42437, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n"}
{"id": 42438, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n"}
{"id": 42439, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n"}
{"id": 42440, "name": "Entropy_Narcissist", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n"}
{"id": 42441, "name": "Entropy_Narcissist", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n"}
{"id": 42442, "name": "DNS query", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n", "Java": "import java.net.InetAddress;\nimport java.net.Inet4Address;\nimport java.net.Inet6Address;\nimport java.net.UnknownHostException;\n\nclass DnsQuery {\n    public static void main(String[] args) {\n        try {\n            InetAddress[] ipAddr = InetAddress.getAllByName(\"www.kame.net\");\n            for(int i=0; i < ipAddr.length ; i++) {\n                if (ipAddr[i] instanceof Inet4Address) {\n                    System.out.println(\"IPv4 : \" + ipAddr[i].getHostAddress());\n                } else if (ipAddr[i] instanceof Inet6Address) {\n                    System.out.println(\"IPv6 : \" + ipAddr[i].getHostAddress());\n                }\n            }\n        } catch (UnknownHostException uhe) {\n            System.err.println(\"unknown host\");\n        }\n    }\n}\n"}
{"id": 42443, "name": "Peano curve", "Python": "import turtle as tt\nimport inspect\n\nstack = [] \ndef peano(iterations=1):\n    global stack\n\n    \n    ivan = tt.Turtle(shape = \"classic\", visible = True)\n\n\n    \n    screen = tt.Screen()\n    screen.title(\"Desenhin do Peano\")\n    screen.bgcolor(\"\n    screen.delay(0) \n    screen.setup(width=0.95, height=0.9)\n\n    \n    walk = 1\n\n    def screenlength(k):\n        \n        \n        if k != 0:\n            length = screenlength(k-1)\n            return 2*length + 1\n        else: return 0\n\n    kkkj = screenlength(iterations)\n    screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)\n    ivan.color(\"\n\n\n    \n    def step1(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n    def step2(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n\n    \n    ivan.left(90)\n    step2(iterations)\n\n    tt.done()\n\nif __name__ == \"__main__\":\n    peano(4)\n    import pylab as P \n    P.plot(stack)\n    P.show()\n", "Java": "import java.io.*;\n\npublic class PeanoCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"peano_curve.svg\"))) {\n            PeanoCurve s = new PeanoCurve(writer);\n            final int length = 8;\n            s.currentAngle = 90;\n            s.currentX = length;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(656);\n            s.execute(rewrite(4));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private PeanoCurve(final Writer writer) {\n        this.writer = writer;\n    }\n\n    private void begin(final int size) throws IOException {\n        write(\"<svg xmlns='http:\n        write(\"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n        write(\"<path stroke-width='1' stroke='black' fill='none' d='\");\n    }\n\n    private void end() throws IOException {\n        write(\"'/>\\n</svg>\\n\");\n    }\n\n    private void execute(final String s) throws IOException {\n        write(\"M%g,%g\\n\", currentX, currentY);\n        for (int i = 0, n = s.length(); i < n; ++i) {\n            switch (s.charAt(i)) {\n                case 'F':\n                    line(lineLength);\n                    break;\n                case '+':\n                    turn(ANGLE);\n                    break;\n                case '-':\n                    turn(-ANGLE);\n                    break;\n            }\n        }\n    }\n\n    private void line(final double length) throws IOException {\n        final double theta = (Math.PI * currentAngle) / 180.0;\n        currentX += length * Math.cos(theta);\n        currentY += length * Math.sin(theta);\n        write(\"L%g,%g\\n\", currentX, currentY);\n    }\n\n    private void turn(final int angle) {\n        currentAngle = (currentAngle + angle) % 360;\n    }\n\n    private void write(final String format, final Object... args) throws IOException {\n        writer.write(String.format(format, args));\n    }\n\n    private static String rewrite(final int order) {\n        String s = \"L\";\n        for (int i = 0; i < order; ++i) {\n            final StringBuilder sb = new StringBuilder();\n            for (int j = 0, n = s.length(); j < n; ++j) {\n                final char ch = s.charAt(j);\n                if (ch == 'L')\n                    sb.append(\"LFRFL-F-RFLFR+F+LFRFL\");\n                else if (ch == 'R')\n                    sb.append(\"RFLFR+F+LFRFL-F-RFLFR\");\n                else\n                    sb.append(ch);\n            }\n            s = sb.toString();\n        }\n        return s;\n    }\n\n    private final Writer writer;\n    private double lineLength;\n    private double currentX;\n    private double currentY;\n    private int currentAngle;\n    private static final int ANGLE = 90;\n}\n"}
{"id": 42444, "name": "Seven-sided dice from five-sided dice", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n", "Java": "import java.util.Random;\npublic class SevenSidedDice \n{\n\tprivate static final Random rnd = new Random();\n\tpublic static void main(String[] args)\n\t{\n\t\tSevenSidedDice now=new SevenSidedDice();\n\t\tSystem.out.println(\"Random number from 1 to 7: \"+now.seven());\n\t}\n\tint seven()\n\t{\n\t\tint v=21;\n\t\twhile(v>20)\n\t\t\tv=five()+five()*5-6;\n\t\treturn 1+v%7;\n\t}\n\tint five()\n\t{\n\t\treturn 1+rnd.nextInt(5);\n\t}\n}\n"}
{"id": 42445, "name": "Solve the no connection puzzle", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\n\npublic class NoConnection {\n\n    \n    static int[][] links = {\n        {2, 3, 4}, \n        {3, 4, 5}, \n        {2, 4},    \n        {5},       \n        {2, 3, 4}, \n        {3, 4, 5}, \n    };\n\n    static int[] pegs = new int[8];\n\n    public static void main(String[] args) {\n\n        List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());\n        do {\n            Collections.shuffle(vals);\n            for (int i = 0; i < pegs.length; i++)\n                pegs[i] = vals.get(i);\n\n        } while (!solved());\n\n        printResult();\n    }\n\n    static boolean solved() {\n        for (int i = 0; i < links.length; i++)\n            for (int peg : links[i])\n                if (abs(pegs[i] - peg) == 1)\n                    return false;\n        return true;\n    }\n\n    static void printResult() {\n        System.out.printf(\"  %s %s%n\", pegs[0], pegs[1]);\n        System.out.printf(\"%s %s %s %s%n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n        System.out.printf(\"  %s %s%n\", pegs[6], pegs[7]);\n    }\n}\n"}
{"id": 42446, "name": "Solve the no connection puzzle", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\n\npublic class NoConnection {\n\n    \n    static int[][] links = {\n        {2, 3, 4}, \n        {3, 4, 5}, \n        {2, 4},    \n        {5},       \n        {2, 3, 4}, \n        {3, 4, 5}, \n    };\n\n    static int[] pegs = new int[8];\n\n    public static void main(String[] args) {\n\n        List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());\n        do {\n            Collections.shuffle(vals);\n            for (int i = 0; i < pegs.length; i++)\n                pegs[i] = vals.get(i);\n\n        } while (!solved());\n\n        printResult();\n    }\n\n    static boolean solved() {\n        for (int i = 0; i < links.length; i++)\n            for (int peg : links[i])\n                if (abs(pegs[i] - peg) == 1)\n                    return false;\n        return true;\n    }\n\n    static void printResult() {\n        System.out.printf(\"  %s %s%n\", pegs[0], pegs[1]);\n        System.out.printf(\"%s %s %s %s%n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n        System.out.printf(\"  %s %s%n\", pegs[6], pegs[7]);\n    }\n}\n"}
{"id": 42447, "name": "Extensible prime generator", "Python": "islice(count(7), 0, None, 2)\n", "Java": "import java.util.*;\n\npublic class PrimeGenerator {\n    private int limit_;\n    private int index_ = 0;\n    private int increment_;\n    private int count_ = 0;\n    private List<Integer> primes_ = new ArrayList<>();\n    private BitSet sieve_ = new BitSet();\n    private int sieveLimit_ = 0;\n\n    public PrimeGenerator(int initialLimit, int increment) {\n        limit_ = nextOddNumber(initialLimit);\n        increment_ = increment;\n        primes_.add(2);\n        findPrimes(3);\n    }\n\n    public int nextPrime() {\n        if (index_ == primes_.size()) {\n            if (Integer.MAX_VALUE - increment_ < limit_)\n                return 0;\n            int start = limit_ + 2;\n            limit_ = nextOddNumber(limit_ + increment_);\n            primes_.clear();\n            findPrimes(start);\n        }\n        ++count_;\n        return primes_.get(index_++);\n    }\n\n    public int count() {\n        return count_;\n    }\n\n    private void findPrimes(int start) {\n        index_ = 0;\n        int newLimit = sqrt(limit_);\n        for (int p = 3; p * p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p));\n            for (; q <= newLimit; q += 2*p)\n                sieve_.set(q/2 - 1, true);\n        }\n        sieveLimit_ = newLimit;\n        int count = (limit_ - start)/2 + 1;\n        BitSet composite = new BitSet(count);\n        for (int p = 3; p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start;\n            q /= 2;\n            for (; q >= 0 && q < count; q += p)\n                composite.set(q, true);\n        }\n        for (int p = 0; p < count; ++p) {\n            if (!composite.get(p))\n                primes_.add(p * 2 + start);\n        }\n    }\n\n    private static int sqrt(int n) {\n        return nextOddNumber((int)Math.sqrt(n));\n    }\n\n    private static int nextOddNumber(int n) {\n        return 1 + 2 * (n/2);\n    }\n\n    public static void main(String[] args) {\n        PrimeGenerator pgen = new PrimeGenerator(20, 200000);\n        System.out.println(\"First 20 primes:\");\n        for (int i = 0; i < 20; ++i) {\n            if (i > 0)\n                System.out.print(\", \");\n            System.out.print(pgen.nextPrime());\n        }\n        System.out.println();\n        System.out.println(\"Primes between 100 and 150:\");\n        for (int i = 0; ; ) {\n            int prime = pgen.nextPrime();\n            if (prime > 150)\n                break;\n            if (prime >= 100) {\n                if (i++ != 0)\n                    System.out.print(\", \");\n                System.out.print(prime);\n            }\n        }\n        System.out.println();\n        int count = 0;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime > 8000)\n                break;\n            if (prime >= 7700)\n                ++count;\n        }\n        System.out.println(\"Number of primes between 7700 and 8000: \" + count);\n        int n = 10000;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime == 0) {\n                System.out.println(\"Can't generate any more primes.\");\n                break;\n            }\n            if (pgen.count() == n) {\n                System.out.println(n + \"th prime: \" + prime);\n                n *= 10;\n            }\n        }\n    }\n}\n"}
{"id": 42448, "name": "Rock-paper-scissors", "Python": "from random import choice\n\nrules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}\nprevious = ['rock', 'paper', 'scissors']\n\nwhile True:\n    human = input('\\nchoose your weapon: ')\n    computer = rules[choice(previous)]  \n\n    if human in ('quit', 'exit'): break\n\n    elif human in rules:\n        previous.append(human)\n        print('the computer played', computer, end='; ')\n\n        if rules[computer] == human:  \n            print('yay you win!')\n        elif rules[human] == computer:  \n            print('the computer beat you... :(')\n        else: print(\"it's a tie!\")\n\n    else: print(\"that's not a valid choice\")\n", "Java": "import java.util.Arrays;\nimport java.util.EnumMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Random;\n\npublic class RPS {\n\tpublic enum Item{\n\t\tROCK, PAPER, SCISSORS, ;\n\t\tpublic List<Item> losesToList;\n\t\tpublic boolean losesTo(Item other) {\n\t\t\treturn losesToList.contains(other);\n\t\t}\n\t\tstatic {\n\t\t\tSCISSORS.losesToList = Arrays.asList(ROCK);\n\t\t\tROCK.losesToList = Arrays.asList(PAPER);\n\t\t\tPAPER.losesToList = Arrays.asList(SCISSORS);\n\t\t\t\n                }\n\t}\n\t\n\tpublic final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{\n\t\tfor(Item item:Item.values())\n\t\t\tput(item, 1);\n\t}};\n\n\tprivate int totalThrows = Item.values().length;\n\n\tpublic static void main(String[] args){\n\t\tRPS rps = new RPS();\n\t\trps.run();\n\t}\n\n\tpublic void run() {\n\t\tScanner in = new Scanner(System.in);\n\t\tSystem.out.print(\"Make your choice: \");\n\t\twhile(in.hasNextLine()){\n\t\t\tItem aiChoice = getAIChoice();\n\t\t\tString input = in.nextLine();\n\t\t\tItem choice;\n\t\t\ttry{\n\t\t\t\tchoice = Item.valueOf(input.toUpperCase());\n\t\t\t}catch (IllegalArgumentException ex){\n\t\t\t\tSystem.out.println(\"Invalid choice\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcounts.put(choice, counts.get(choice) + 1);\n\t\t\ttotalThrows++;\n\t\t\tSystem.out.println(\"Computer chose: \" + aiChoice);\n\t\t\tif(aiChoice == choice){\n\t\t\t\tSystem.out.println(\"Tie!\");\n\t\t\t}else if(aiChoice.losesTo(choice)){\n\t\t\t\tSystem.out.println(\"You chose...wisely. You win!\");\n\t\t\t}else{\n\t\t\t\tSystem.out.println(\"You chose...poorly. You lose!\");\n\t\t\t}\n\t\t\tSystem.out.print(\"Make your choice: \");\n\t\t}\n\t}\n\n\tprivate static final Random rng = new Random();\n\tprivate Item getAIChoice() {\n\t\tint rand = rng.nextInt(totalThrows);\n\t\tfor(Map.Entry<Item, Integer> entry:counts.entrySet()){\n\t\t\tItem item = entry.getKey();\n\t\t\tint count = entry.getValue();\n\t\t\tif(rand < count){\n\t\t\t\tList<Item> losesTo = item.losesToList;\n\t\t\t\treturn losesTo.get(rng.nextInt(losesTo.size()));\n\t\t\t}\n\t\t\trand -= count;\n\t\t}\n\t\treturn null;\n\t}\n}\n"}
{"id": 42449, "name": "Create a two-dimensional array at runtime", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n", "Java": "import java.util.Scanner;\n\npublic class twoDimArray {\n  public static void main(String[] args) {\n        Scanner in = new Scanner(System.in);\n        \n        int nbr1 = in.nextInt();\n        int nbr2 = in.nextInt();\n        \n        double[][] array = new double[nbr1][nbr2];\n        array[0][0] = 42.0;\n        System.out.println(\"The number at place [0 0] is \" + array[0][0]);\n  }\n}\n"}
{"id": 42450, "name": "Chinese remainder theorem", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n"}
{"id": 42451, "name": "Chinese remainder theorem", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n"}
{"id": 42452, "name": "Vigenère cipher_Cryptanalysis", "Python": "from string import uppercase\nfrom operator import itemgetter\n\ndef vigenere_decrypt(target_freqs, input):\n    nchars = len(uppercase)\n    ordA = ord('A')\n    sorted_targets = sorted(target_freqs)\n\n    def frequency(input):\n        result = [[c, 0.0] for c in uppercase]\n        for c in input:\n            result[c - ordA][1] += 1\n        return result\n\n    def correlation(input):\n        result = 0.0\n        freq = frequency(input)\n        freq.sort(key=itemgetter(1))\n\n        for i, f in enumerate(freq):\n            result += f[1] * sorted_targets[i]\n        return result\n\n    cleaned = [ord(c) for c in input.upper() if c.isupper()]\n    best_len = 0\n    best_corr = -100.0\n\n    \n    \n    for i in xrange(2, len(cleaned) // 20):\n        pieces = [[] for _ in xrange(i)]\n        for j, c in enumerate(cleaned):\n            pieces[j % i].append(c)\n\n        \n        \n        corr = -0.5 * i + sum(correlation(p) for p in pieces)\n\n        if corr > best_corr:\n            best_len = i\n            best_corr = corr\n\n    if best_len == 0:\n        return (\"Text is too short to analyze\", \"\")\n\n    pieces = [[] for _ in xrange(best_len)]\n    for i, c in enumerate(cleaned):\n        pieces[i % best_len].append(c)\n\n    freqs = [frequency(p) for p in pieces]\n\n    key = \"\"\n    for fr in freqs:\n        fr.sort(key=itemgetter(1), reverse=True)\n\n        m = 0\n        max_corr = 0.0\n        for j in xrange(nchars):\n            corr = 0.0\n            c = ordA + j\n            for frc in fr:\n                d = (ord(frc[0]) - c + nchars) % nchars\n                corr += frc[1] * target_freqs[d]\n\n            if corr > max_corr:\n                m = j\n                max_corr = corr\n\n        key += chr(m + ordA)\n\n    r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)\n         for i, c in enumerate(cleaned))\n    return (key, \"\".join(r))\n\n\ndef main():\n    encoded = \n\n    english_frequences = [\n        0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n        0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n        0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n        0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\n    (key, decoded) = vigenere_decrypt(english_frequences, encoded)\n    print \"Key:\", key\n    print \"\\nText:\", decoded\n\nmain()\n", "Java": "public class Vig{\nstatic String encodedMessage =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n \nfinal static double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n \n\npublic static void main(String[] args) {\n    int lenghtOfEncodedMessage = encodedMessage.length();\n    char[] encoded = new char [lenghtOfEncodedMessage] ;\n    char[] key =  new char [lenghtOfEncodedMessage] ;\n\n    encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0);\n    int txt[] = new int[lenghtOfEncodedMessage];\n    int len = 0, j;\n\n    double fit, best_fit = 1e100;\n \n    for (j = 0; j < lenghtOfEncodedMessage; j++)\n        if (Character.isUpperCase(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n \n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        System.out.printf(\"%f, key length: %2d \", fit, j);\n            System.out.print(key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            System.out.print(\" <--- best so far\");\n        }\n        System.out.print(\"\\n\");\n\n    }\n}\n\n\n    static String decrypt(String text, final String key) {\n        String res = \"\";\n        text = text.toUpperCase();\n        for (int i = 0, j = 0; i < text.length(); i++) {\n            char c = text.charAt(i);\n            if (c < 'A' || c > 'Z') continue;\n            res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n            j = ++j % key.length();\n        }\n        return res;\n    }\n\nstatic int best_match(final double []a, final double []b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n \n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n \n    return best_rotate;\n}\n \nstatic double freq_every_nth(final int []msg, int len, int interval, char[] key) {\n    double sum, d, ret;\n    double  [] accu = new double [26];\n    double  [] out = new double [26];\n    int i, j, rot;\n \n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n\trot = best_match(out, freq);\n\ttry{\n            key[j] = (char)(rot + 'A');\n\t} catch (Exception e) {\n\t\tSystem.out.print(e.getMessage());\n\t}\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n \n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n \n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n \n    key[interval] = '\\0';\n    return ret;\n}\n \n}\n"}
{"id": 42453, "name": "Pi", "Python": "def calcPi():\n    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n    while True:\n        if 4*q+r-t < n*t:\n            yield n\n            nr = 10*(r-n*t)\n            n  = ((10*(3*q+r))//t)-10*n\n            q  *= 10\n            r  = nr\n        else:\n            nr = (2*q+r)*l\n            nn = (q*(7*k)+2+(r*l))//(t*l)\n            q  *= k\n            t  *= l\n            l  += 2\n            k += 1\n            n  = nn\n            r  = nr\n\nimport sys\npi_digits = calcPi()\ni = 0\nfor d in pi_digits:\n    sys.stdout.write(str(d))\n    i += 1\n    if i == 40: print(\"\"); i = 0\n", "Java": "import java.math.BigInteger ;\n\npublic class Pi {\n  final BigInteger TWO = BigInteger.valueOf(2) ;\n  final BigInteger THREE = BigInteger.valueOf(3) ;\n  final BigInteger FOUR = BigInteger.valueOf(4) ;\n  final BigInteger SEVEN = BigInteger.valueOf(7) ;\n\n  BigInteger q = BigInteger.ONE ;\n  BigInteger r = BigInteger.ZERO ;\n  BigInteger t = BigInteger.ONE ;\n  BigInteger k = BigInteger.ONE ;\n  BigInteger n = BigInteger.valueOf(3) ;\n  BigInteger l = BigInteger.valueOf(3) ;\n\n  public void calcPiDigits(){\n    BigInteger nn, nr ;\n    boolean first = true ;\n    while(true){\n        if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){\n          System.out.print(n) ;\n          if(first){System.out.print(\".\") ; first = false ;}\n          nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ;\n          n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ;\n          q = q.multiply(BigInteger.TEN) ;\n          r = nr ;\n          System.out.flush() ;\n        }else{\n          nr = TWO.multiply(q).add(r).multiply(l) ;\n          nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ;\n          q = q.multiply(k) ;\n          t = t.multiply(l) ;\n          l = l.add(TWO) ;\n          k = k.add(BigInteger.ONE) ;\n          n = nn ;\n          r = nr ;\n        }\n    }\n  }\n\n  public static void main(String[] args) {\n    Pi p = new Pi() ;\n    p.calcPiDigits() ;\n  }\n}\n"}
{"id": 42454, "name": "Hofstadter Q sequence", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n"}
{"id": 42455, "name": "Hofstadter Q sequence", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n"}
{"id": 42456, "name": "Y combinator", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))\n>>> [ Y(fac)(i) for i in range(10) ]\n[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]\n>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))\n>>> [ Y(fib)(i) for i in range(10) ]\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "Java": "import java.util.function.Function;\n\npublic interface YCombinator {\n  interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }\n  public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {\n    RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));\n    return r.apply(r);\n  }\n\n  public static void main(String... arguments) {\n    Function<Integer,Integer> fib = Y(f -> n ->\n      (n <= 2)\n        ? 1\n        : (f.apply(n - 1) + f.apply(n - 2))\n    );\n    Function<Integer,Integer> fac = Y(f -> n ->\n      (n <= 1)\n        ? 1\n        : (n * f.apply(n - 1))\n    );\n\n    System.out.println(\"fib(10) = \" + fib.apply(10));\n    System.out.println(\"fac(10) = \" + fac.apply(10));\n  }\n}\n"}
{"id": 42457, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\n\npublic class RReturnMultipleVals {\n  public static final String K_lipsum = \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n  public static final Long   K_1024   = 1024L;\n  public static final String L        = \"L\";\n  public static final String R        = \"R\";\n\n  \n  public static void main(String[] args) throws NumberFormatException{\n    Long nv_;\n    String sv_;\n    switch (args.length) {\n      case 0:\n        nv_ = K_1024;\n        sv_ = K_lipsum;\n        break;\n      case 1:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = K_lipsum;\n        break;\n      case 2:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        break;\n      default:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        for (int ix = 2; ix < args.length; ++ix) {\n          sv_ = sv_ + \" \" + args[ix];\n        }\n        break;\n    }\n\n    RReturnMultipleVals lcl = new RReturnMultipleVals();\n\n    Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); \n    System.out.println(\"Results extracted from a composite object:\");\n    System.out.printf(\"%s, %s%n%n\", rvp.getLeftVal(), rvp.getRightVal());\n\n    List<Object> rvl = lcl.getPairFromList(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"List\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvl.get(0), rvl.get(1));\n\n    Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"Map\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvm.get(L), rvm.get(R));\n  }\n  \n  \n  \n  public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {\n    return new Pair<T, U>(vl_, vr_);\n  }\n  \n  \n  \n  public List<Object> getPairFromList(Object nv_, Object sv_) {\n    List<Object> rset = new ArrayList<Object>();\n    rset.add(nv_);\n    rset.add(sv_);\n    return rset;\n  }\n  \n  \n  \n  public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {\n    Map<String, Object> rset = new HashMap<String, Object>();\n    rset.put(L, nv_);\n    rset.put(R, sv_);\n    return rset;\n  }\n\n  \n  private static class Pair<L, R> {\n    private L leftVal;\n    private R rightVal;\n\n    public Pair(L nv_, R sv_) {\n      setLeftVal(nv_);\n      setRightVal(sv_);\n    }\n    public void setLeftVal(L nv_) {\n      leftVal = nv_;\n    }\n    public L getLeftVal() {\n      return leftVal;\n    }\n    public void setRightVal(R sv_) {\n      rightVal = sv_;\n    }\n    public R getRightVal() {\n      return rightVal;\n    }\n  }\n}\n"}
{"id": 42458, "name": "Van Eck sequence", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n"}
{"id": 42459, "name": "Van Eck sequence", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n"}
{"id": 42460, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 42461, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 42462, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 42463, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 42464, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 42465, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 42466, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 42467, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 42468, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 42469, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 42470, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 42471, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 42472, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42473, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42474, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42475, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 42476, "name": "LZW compression", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 42477, "name": "LZW compression", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 42478, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 42479, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 42480, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42481, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42482, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42483, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 42484, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 42485, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 42486, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 42487, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 42488, "name": "Sorting algorithms_Strand sort", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 42489, "name": "Sorting algorithms_Strand sort", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 42490, "name": "Delegates", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 42491, "name": "Delegates", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 42492, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42493, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42494, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42495, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 42496, "name": "Enforced immutability", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 42497, "name": "Enforced immutability", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 42498, "name": "Sutherland-Hodgman polygon clipping", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 42499, "name": "Sutherland-Hodgman polygon clipping", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 42500, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 42501, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 42502, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42503, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42504, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42505, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 42506, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42507, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42508, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42509, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 42510, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 42511, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 42512, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 42513, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 42514, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 42515, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 42516, "name": "First-class functions", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 42517, "name": "First-class functions", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 42518, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 42519, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 42520, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 42521, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 42522, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 42523, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 42524, "name": "Fractal tree", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 42525, "name": "Fractal tree", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 42526, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42527, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42528, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42529, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 42530, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 42531, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 42532, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 42533, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 42534, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 42535, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 42536, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 42537, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 42538, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 42539, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 42540, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 42541, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 42542, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 42543, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 42544, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 42545, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 42546, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 42547, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 42548, "name": "Sorting algorithms_Shell sort", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 42549, "name": "Sorting algorithms_Shell sort", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 42550, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 42551, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 42552, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 42553, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 42554, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 42555, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 42556, "name": "Sorting algorithms_Permutation sort", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 42557, "name": "Sorting algorithms_Permutation sort", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 42558, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 42559, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 42560, "name": "Entropy", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 42561, "name": "Entropy", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 42562, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n"}
{"id": 42563, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n"}
{"id": 42564, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 42565, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 42566, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 42567, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 42568, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 42569, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 42570, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 42571, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 42572, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 42573, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 42574, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 42575, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 42576, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n"}
{"id": 42577, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n"}
{"id": 42578, "name": "String interpolation (included)", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 42579, "name": "Bitwise operations", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n"}
{"id": 42580, "name": "Dragon curve", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n"}
{"id": 42581, "name": "Read a file line by line", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n"}
{"id": 42582, "name": "Doubly-linked list_Element insertion", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n"}
{"id": 42583, "name": "Quickselect algorithm", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 42584, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n"}
{"id": 42585, "name": "Walk a directory_Recursively", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n"}
{"id": 42586, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 42587, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 42588, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 42589, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n"}
{"id": 42590, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 42591, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 42592, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 42593, "name": "LZW compression", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n"}
{"id": 42594, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 42595, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 42596, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 42597, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 42598, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42599, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42600, "name": "Anonymous recursion", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 42601, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 42602, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 42603, "name": "Longest string challenge", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n"}
{"id": 42604, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 42605, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 42606, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 42607, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n"}
{"id": 42608, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 42609, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 42610, "name": "Dining philosophers", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n"}
{"id": 42611, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 42612, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 42613, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42614, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42615, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42616, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 42617, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 42618, "name": "Spiral matrix", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 42619, "name": "Spiral matrix", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 42620, "name": "Optional parameters", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n"}
{"id": 42621, "name": "Call a foreign-language function", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n"}
{"id": 42622, "name": "Faulhaber's triangle", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n"}
{"id": 42623, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 42624, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 42625, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 42626, "name": "Word wheel", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n"}
{"id": 42627, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n"}
{"id": 42628, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42629, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42630, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 42631, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 42632, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 42633, "name": "Primes - allocate descendants to their ancestors", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n"}
{"id": 42634, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 42635, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 42636, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 42637, "name": "Proper divisors", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 42638, "name": "XML_Output", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n"}
{"id": 42639, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 42640, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 42641, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n"}
{"id": 42642, "name": "Hash from two arrays", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n"}
{"id": 42643, "name": "Colour pinstripe_Display", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n"}
{"id": 42644, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n"}
{"id": 42645, "name": "Animate a pendulum", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 42646, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 42647, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 42648, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n"}
{"id": 42649, "name": "Arrays", "VB": "Option Base {0|1}\n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 42650, "name": "Sierpinski carpet", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 42651, "name": "Sorting algorithms_Bogosort", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n"}
{"id": 42652, "name": "Euler method", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n"}
{"id": 42653, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 42654, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 42655, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42656, "name": "JortSort", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n"}
{"id": 42657, "name": "Leap year", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n"}
{"id": 42658, "name": "Combinations and permutations", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n"}
{"id": 42659, "name": "Sort numbers lexicographically", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n"}
{"id": 42660, "name": "Number names", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n"}
{"id": 42661, "name": "Sorting algorithms_Shell sort", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 42662, "name": "Doubly-linked list_Definition", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n"}
{"id": 42663, "name": "Letter frequency", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 42664, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n"}
{"id": 42665, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 42666, "name": "Averages_Arithmetic mean", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 42667, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42668, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42669, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 42670, "name": "Tokenize a string with escaping", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n"}
{"id": 42671, "name": "Forward difference", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n"}
{"id": 42672, "name": "Primality by trial division", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n"}
{"id": 42673, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n"}
{"id": 42674, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n"}
{"id": 42675, "name": "Singly-linked list_Traversal", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n"}
{"id": 42676, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n"}
{"id": 42677, "name": "Dragon curve", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n"}
{"id": 42678, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n"}
{"id": 42679, "name": "Doubly-linked list_Element insertion", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n"}
{"id": 42680, "name": "Smarandache prime-digital sequence", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n"}
{"id": 42681, "name": "Quickselect algorithm", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 42682, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n"}
{"id": 42683, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n"}
{"id": 42684, "name": "State name puzzle", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n"}
{"id": 42685, "name": "State name puzzle", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n"}
{"id": 42686, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n"}
{"id": 42687, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 42688, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 42689, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n"}
{"id": 42690, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 42691, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 42692, "name": "LZW compression", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n"}
{"id": 42693, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 42694, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 42695, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 42696, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 42697, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 42698, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 42699, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 42700, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 42701, "name": "Mertens function", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n"}
{"id": 42702, "name": "Order by pair comparisons", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n"}
{"id": 42703, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 42704, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 42705, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 42706, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 42707, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 42708, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n"}
{"id": 42709, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 42710, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 42711, "name": "Legendre prime counting function", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n"}
{"id": 42712, "name": "Use another language to call a function", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n"}
{"id": 42713, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n"}
{"id": 42714, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n"}
{"id": 42715, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 42716, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 42717, "name": "Unprimeable numbers", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n"}
{"id": 42718, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 42719, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 42720, "name": "Chernick's Carmichael numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 42721, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 42722, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 42723, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 42724, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 42725, "name": "Sequence of primorial primes", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 42726, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 42727, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 42728, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 42729, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 42730, "name": "Dining philosophers", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n"}
{"id": 42731, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 42732, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 42733, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 42734, "name": "Logistic curve fitting in epidemiology", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n"}
{"id": 42735, "name": "Sorting algorithms_Strand sort", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n"}
{"id": 42736, "name": "Additive primes", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n"}
{"id": 42737, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 42738, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 42739, "name": "Delegates", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n"}
{"id": 42740, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 42741, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 42742, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 42743, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 42744, "name": "Enforced immutability", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n"}
{"id": 42745, "name": "Sutherland-Hodgman polygon clipping", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42746, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 42747, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 42748, "name": "Spiral matrix", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n"}
{"id": 42749, "name": "Optional parameters", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n"}
{"id": 42750, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 42751, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 42752, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n"}
{"id": 42753, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 42754, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 42755, "name": "Faulhaber's triangle", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n"}
{"id": 42756, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 42757, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 42758, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"}
{"id": 42759, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 42760, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 42761, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 42762, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 42763, "name": "Primes - allocate descendants to their ancestors", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n"}
{"id": 42764, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 42765, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 42766, "name": "First-class functions", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n"}
{"id": 42767, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n"}
{"id": 42768, "name": "XML_Output", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 42769, "name": "XML_Output", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 42770, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 42771, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 42772, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 42773, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n"}
{"id": 42774, "name": "Guess the number_With feedback (player)", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n"}
{"id": 42775, "name": "Guess the number_With feedback (player)", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n"}
{"id": 42776, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n"}
{"id": 42777, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 42778, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 42779, "name": "Fractal tree", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n"}
{"id": 42780, "name": "Colour pinstripe_Display", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n"}
{"id": 42781, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 42782, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 42783, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 42784, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n"}
{"id": 42785, "name": "Animate a pendulum", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n"}
{"id": 42786, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 42787, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 42788, "name": "Create a file on magnetic tape", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n"}
{"id": 42789, "name": "Sorting algorithms_Heapsort", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 42790, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 42791, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 42792, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n"}
{"id": 42793, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 42794, "name": "Euler method", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n"}
{"id": 42795, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 42796, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 42797, "name": "JortSort", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n"}
{"id": 42798, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n"}
{"id": 42799, "name": "Combinations and permutations", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n"}
{"id": 42800, "name": "Sort numbers lexicographically", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n"}
{"id": 42801, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n"}
{"id": 42802, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42803, "name": "Sorting algorithms_Shell sort", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n"}
{"id": 42804, "name": "Doubly-linked list_Definition", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n"}
{"id": 42805, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n"}
{"id": 42806, "name": "Permutation test", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n"}
{"id": 42807, "name": "Möbius function", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 42808, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n"}
{"id": 42809, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 42810, "name": "Sorting algorithms_Permutation sort", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n"}
{"id": 42811, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n"}
{"id": 42812, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 42813, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 42814, "name": "Entropy", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n"}
{"id": 42815, "name": "Tokenize a string with escaping", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n"}
{"id": 42816, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n"}
{"id": 42817, "name": "Sexy primes", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n"}
{"id": 42818, "name": "Sexy primes", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n"}
{"id": 42819, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 42820, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n"}
{"id": 42821, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n"}
{"id": 42822, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n"}
{"id": 42823, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n"}
{"id": 42824, "name": "Singly-linked list_Traversal", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n"}
{"id": 42825, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42826, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n"}
{"id": 42827, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 42828, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"}
{"id": 42829, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"}
{"id": 42830, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n"}
{"id": 42831, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n"}
{"id": 42832, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 42833, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 42834, "name": "String interpolation (included)", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n"}
{"id": 42835, "name": "Sorting algorithms_Patience sort", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <iterator>\n#include <algorithm>\n#include <cassert>\n\ntemplate <class E>\nstruct pile_less {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() < pile2.top();\n  }\n};\n\ntemplate <class E>\nstruct pile_greater {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() > pile2.top();\n  }\n};\n\n\ntemplate <class Iterator>\nvoid patience_sort(Iterator first, Iterator last) {\n  typedef typename std::iterator_traits<Iterator>::value_type E;\n  typedef std::stack<E> Pile;\n\n  std::vector<Pile> piles;\n  \n  for (Iterator it = first; it != last; it++) {\n    E& x = *it;\n    Pile newPile;\n    newPile.push(x);\n    typename std::vector<Pile>::iterator i =\n      std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());\n    if (i != piles.end())\n      i->push(x);\n    else\n      piles.push_back(newPile);\n  }\n\n  \n  \n  std::make_heap(piles.begin(), piles.end(), pile_greater<E>());\n  for (Iterator it = first; it != last; it++) {\n    std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());\n    Pile &smallPile = piles.back();\n    *it = smallPile.top();\n    smallPile.pop();\n    if (smallPile.empty())\n      piles.pop_back();\n    else\n      std::push_heap(piles.begin(), piles.end(), pile_greater<E>());\n  }\n  assert(piles.empty());\n}\n\nint main() {\n  int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n  patience_sort(a, a+sizeof(a)/sizeof(*a));\n  std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  return 0;\n}\n"}
{"id": 42836, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n"}
{"id": 42837, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n"}
{"id": 42838, "name": "Tau number", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"The first \" << limit << \" tau numbers are:\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            std::cout << std::setw(6) << n;\n            ++count;\n            if (count % 10 == 0)\n                std::cout << '\\n';\n        }\n    }\n}\n"}
{"id": 42839, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n"}
{"id": 42840, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n"}
{"id": 42841, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n"}
{"id": 42842, "name": "Partition function P", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n"}
{"id": 42843, "name": "Ray-casting algorithm", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nconst double epsilon = numeric_limits<float>().epsilon();\nconst numeric_limits<double> DOUBLE;\nconst double MIN = DOUBLE.min();\nconst double MAX = DOUBLE.max();\n\nstruct Point { const double x, y; };\n\nstruct Edge {\n    const Point a, b;\n\n    bool operator()(const Point& p) const\n    {\n        if (a.y > b.y) return Edge{ b, a }(p);\n        if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });\n        if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;\n        if (p.x < min(a.x, b.x)) return true;\n        auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;\n        auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;\n        return blue >= red;\n    }\n};\n\nstruct Figure {\n    const string  name;\n    const initializer_list<Edge> edges;\n\n    bool contains(const Point& p) const\n    {\n        auto c = 0;\n        for (auto e : edges) if (e(p)) c++;\n        return c % 2 != 0;\n    }\n\n    template<unsigned char W = 3>\n    void check(const initializer_list<Point>& points, ostream& os) const\n    {\n        os << \"Is point inside figure \" << name <<  '?' << endl;\n        for (auto p : points)\n            os << \"  (\" << setw(W) << p.x << ',' << setw(W) << p.y << \"): \" << boolalpha << contains(p) << endl;\n        os << endl;\n    }\n};\n\nint main()\n{\n    const initializer_list<Point> points =  { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };\n    const Figure square = { \"Square\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }\n    };\n\n    const Figure square_hole = { \"Square hole\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},\n           {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure strange = { \"Strange\",\n        {  {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},\n           {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure exagon = { \"Exagon\",\n        {  {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},\n           {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}\n        }\n    };\n\n    for(auto f : {square, square_hole, strange, exagon})\n        f.check(points, cout);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42844, "name": "Elliptic curve arithmetic", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n"}
{"id": 42845, "name": "Elliptic curve arithmetic", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n"}
{"id": 42846, "name": "Count occurrences of a substring", "Java": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) / subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n", "C++": "#include <iostream>\n#include <string>\n\n\nint countSubstring(const std::string& str, const std::string& sub)\n{\n    if (sub.length() == 0) return 0;\n    int count = 0;\n    for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n    {\n        ++count;\n    }\n    return count;\n}\n\nint main()\n{\n    std::cout << countSubstring(\"the three truths\", \"th\")    << '\\n';\n    std::cout << countSubstring(\"ababababab\", \"abab\")        << '\\n';\n    std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n    return 0;\n}\n"}
{"id": 42847, "name": "Numbers with prime digits whose sum is 13", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n"}
{"id": 42848, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n"}
{"id": 42849, "name": "Dragon curve", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n"}
{"id": 42850, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n"}
{"id": 42851, "name": "Doubly-linked list_Element insertion", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n"}
{"id": 42852, "name": "Quickselect algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 42853, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 42854, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 42855, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 42856, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 42857, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n"}
{"id": 42858, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 42859, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 42860, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 42861, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 42862, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n"}
{"id": 42863, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 42864, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 42865, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n"}
{"id": 42866, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 42867, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 42868, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 42869, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 42870, "name": "Spiral matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n"}
{"id": 42871, "name": "Faulhaber's triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 42872, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 42873, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 42874, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 42875, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n"}
{"id": 42876, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 42877, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 42878, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 42879, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 42880, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n"}
{"id": 42881, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 42882, "name": "XML_Output", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n"}
{"id": 42883, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n"}
{"id": 42884, "name": "Guess the number_With feedback (player)", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n"}
{"id": 42885, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n"}
{"id": 42886, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 42887, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 42888, "name": "Animate a pendulum", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n"}
{"id": 42889, "name": "Sorting algorithms_Heapsort", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n"}
{"id": 42890, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 42891, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 42892, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n"}
{"id": 42893, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 42894, "name": "Merge and aggregate datasets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n"}
{"id": 42895, "name": "Euler method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 42896, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 42897, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 42898, "name": "JortSort", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n"}
{"id": 42899, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n"}
{"id": 42900, "name": "Sort numbers lexicographically", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n"}
{"id": 42901, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n"}
{"id": 42902, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n"}
{"id": 42903, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 42904, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 42905, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 42906, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 42907, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n"}
{"id": 42908, "name": "Entropy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n"}
{"id": 42909, "name": "Tokenize a string with escaping", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n"}
{"id": 42910, "name": "Hello world_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 42911, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 42912, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 42913, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 42914, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 42915, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 42916, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n"}
{"id": 42917, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 42918, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n"}
{"id": 42919, "name": "Discordian date", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n"}
{"id": 42920, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 42921, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 42922, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n"}
{"id": 42923, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n"}
{"id": 42924, "name": "Partition function P", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 42925, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 42926, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 42927, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n"}
{"id": 42928, "name": "Angles (geometric), normalization and conversion", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n", "C#": "using System;\n\npublic static class Angles\n{\n    public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);\n\n    public static void Print(params double[] angles) {\n        string[] names = { \"Degrees\", \"Gradians\", \"Mils\", \"Radians\" };\n        Func<double, double> rnd = a => Math.Round(a, 4);\n        Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };\n\n        Func<double, double>[,] convert = {\n            { a => a, DegToGrad, DegToMil, DegToRad },\n            { GradToDeg, a => a, GradToMil, GradToRad },\n            { MilToDeg, MilToGrad, a => a, MilToRad },\n            { RadToDeg, RadToGrad, RadToMil, a => a }\n        };\n\n        Console.WriteLine($@\"{\"Angle\",-12}{\"Normalized\",-12}{\"Unit\",-12}{\n            \"Degrees\",-12}{\"Gradians\",-12}{\"Mils\",-12}{\"Radians\",-12}\");\n\n        foreach (double angle in angles) {\n            for (int i = 0; i < 4; i++) {\n                double nAngle = normal[i](angle);\n\n                Console.WriteLine($@\"{\n                    rnd(angle),-12}{\n                    rnd(nAngle),-12}{\n                    names[i],-12}{\n                    rnd(convert[i, 0](nAngle)),-12}{\n                    rnd(convert[i, 1](nAngle)),-12}{\n                    rnd(convert[i, 2](nAngle)),-12}{\n                    rnd(convert[i, 3](nAngle)),-12}\");\n            }\n        }\n    }\n\n    public static double NormalizeDeg(double angle) => Normalize(angle, 360);\n    public static double NormalizeGrad(double angle) => Normalize(angle, 400);\n    public static double NormalizeMil(double angle) => Normalize(angle, 6400);\n    public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);\n\n    private static double Normalize(double angle, double N) {\n        while (angle <= -N) angle += N;\n        while (angle >= N) angle -= N;\n        return angle;\n    }\n\n    public static double DegToGrad(double angle) => angle * 10 / 9;\n    public static double DegToMil(double angle) => angle * 160 / 9;\n    public static double DegToRad(double angle) => angle * Math.PI / 180;\n    \n    public static double GradToDeg(double angle) => angle * 9 / 10;\n    public static double GradToMil(double angle) => angle * 16;\n    public static double GradToRad(double angle) => angle * Math.PI / 200;\n    \n    public static double MilToDeg(double angle) => angle * 9 / 160;\n    public static double MilToGrad(double angle) => angle / 16;\n    public static double MilToRad(double angle) => angle * Math.PI / 3200;\n    \n    public static double RadToDeg(double angle) => angle * 180 / Math.PI;\n    public static double RadToGrad(double angle) => angle * 200 / Math.PI;\n    public static double RadToMil(double angle) => angle * 3200 / Math.PI;\n}\n"}
{"id": 42929, "name": "Find common directory path", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n"}
{"id": 42930, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 42931, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 42932, "name": "Memory allocation", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n", "C#": "using System;\nusing System.Runtime.InteropServices;\n\npublic unsafe class Program\n{\n    public static unsafe void HeapMemory()\n    {\n        const int HEAP_ZERO_MEMORY = 0x00000008;\n        const int size = 1000;\n        int ph = GetProcessHeap();\n        void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);\n        if (pointer == null)\n            throw new OutOfMemoryException();\n        Console.WriteLine(HeapSize(ph, 0, pointer));\n        HeapFree(ph, 0, pointer);\n    }\n\n    public static unsafe void StackMemory()\n    {\n        byte* buffer = stackalloc byte[1000];\n        \n    }\n    public static void Main(string[] args)\n    {\n        HeapMemory();\n        StackMemory();\n    }\n    [DllImport(\"kernel32\")]\n    static extern void* HeapAlloc(int hHeap, int flags, int size);\n    [DllImport(\"kernel32\")]\n    static extern bool HeapFree(int hHeap, int flags, void* block);\n    [DllImport(\"kernel32\")]\n    static extern int GetProcessHeap();\n    [DllImport(\"kernel32\")]\n    static extern int HeapSize(int hHeap, int flags, void* block);\n\n}\n"}
{"id": 42933, "name": "Tic-tac-toe", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaTicTacToe\n{\n  class Program\n  {\n\n    \n    static string[][] Players = new string[][] { \n      new string[] { \"COMPUTER\", \"X\" }, \n      new string[] { \"HUMAN\", \"O\" }     \n    };\n\n    const int Unplayed = -1;\n    const int Computer = 0;\n    const int Human = 1;\n\n    \n    static int[] GameBoard = new int[9];\n\n    static int[] corners = new int[] { 0, 2, 6, 8 };\n\n    static int[][] wins = new int[][] { \n      new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, \n      new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, \n      new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };\n\n\n    \n    static void Main(string[] args)\n    {\n      while (true)\n      {\n        Console.Clear();\n        Console.WriteLine(\"Welcome to Rosetta Code Tic-Tac-Toe for C#.\");\n        initializeGameBoard();\n        displayGameBoard();\n        int currentPlayer = rnd.Next(0, 2);  \n        Console.WriteLine(\"The first move goes to {0} who is playing {1}s.\\n\", playerName(currentPlayer), playerToken(currentPlayer));\n        while (true)\n        {\n          int thisMove = getMoveFor(currentPlayer);\n          if (thisMove == Unplayed)\n          {\n            Console.WriteLine(\"{0}, you've quit the game ... am I that good?\", playerName(currentPlayer));\n            break;\n          }\n          playMove(thisMove, currentPlayer);\n          displayGameBoard();\n          if (isGameWon())\n          {\n            Console.WriteLine(\"{0} has won the game!\", playerName(currentPlayer));\n            break;\n          }\n          else if (isGameTied())\n          {\n            Console.WriteLine(\"Cat game ... we have a tie.\");\n            break;\n          }\n          currentPlayer = getNextPlayer(currentPlayer);\n        }\n        if (!playAgain())\n          return;\n      }\n    }\n\n    \n    static int getMoveFor(int player)\n    {\n      if (player == Human)\n        return getManualMove(player);\n      else\n      {\n        \n        \n        int selectedMove = getSemiRandomMove(player);\n        \n        Console.WriteLine(\"{0} selects position {1}.\", playerName(player), selectedMove + 1);\n        return selectedMove;\n      }\n    }\n\n    static int getManualMove(int player)\n    {\n      while (true)\n      {\n        Console.Write(\"{0}, enter you move (number): \", playerName(player));\n        ConsoleKeyInfo keyInfo = Console.ReadKey();\n        Console.WriteLine();  \n        if (keyInfo.Key == ConsoleKey.Escape)\n          return Unplayed;\n        if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)\n        {\n          int move = keyInfo.KeyChar - '1';  \n          if (GameBoard[move] == Unplayed)\n            return move;\n          else\n            Console.WriteLine(\"Spot {0} is already taken, please select again.\", move + 1);\n        }\n        else\n          Console.WriteLine(\"Illegal move, please select again.\\n\");\n      }\n    }\n\n    static int getRandomMove(int player)\n    {\n      int movesLeft = GameBoard.Count(position => position == Unplayed);\n      int x = rnd.Next(0, movesLeft);\n      for (int i = 0; i < GameBoard.Length; i++)  \n      {\n        if (GameBoard[i] == Unplayed && x < 0)    \n          return i;\n        x--;\n      }\n      return Unplayed;\n    }\n\n    \n    static int getSemiRandomMove(int player)\n    {\n      int posToPlay;\n      if (checkForWinningMove(player, out posToPlay))\n        return posToPlay;\n      if (checkForBlockingMove(player, out posToPlay))\n        return posToPlay;\n      return getRandomMove(player);\n    }\n\n    \n    static int getBestMove(int player)\n    {\n      return -1;\n    }\n\n    static bool checkForWinningMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(player, line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool checkForBlockingMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)\n    {\n      int cnt = 0;\n      posToPlay = int.MinValue;\n      foreach (int pos in line)\n      {\n        if (GameBoard[pos] == player)\n          cnt++;\n        else if (GameBoard[pos] == Unplayed)\n          posToPlay = pos;\n      }\n      return cnt == 2 && posToPlay >= 0;\n    }\n\n    static void playMove(int boardPosition, int player)\n    {\n      GameBoard[boardPosition] = player;\n    }\n\n    static bool isGameWon()\n    {\n      return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));\n    }\n\n    static bool takenBySamePlayer(int a, int b, int c)\n    {\n      return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];\n    }\n\n    static bool isGameTied()\n    {\n      return !GameBoard.Any(spot => spot == Unplayed);\n    }\n\n    \n    static Random rnd = new Random();\n\n    static void initializeGameBoard()\n    {\n      for (int i = 0; i < GameBoard.Length; i++)\n        GameBoard[i] = Unplayed;\n    }\n\n    static string playerName(int player)\n    {\n      return Players[player][0];\n    }\n\n    static string playerToken(int player)\n    {\n      return Players[player][1];\n    }\n\n    static int getNextPlayer(int player)\n    {\n      return (player + 1) % 2;\n    }\n\n    static void displayGameBoard()\n    {\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(0), pieceAt(1), pieceAt(2));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(3), pieceAt(4), pieceAt(5));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(6), pieceAt(7), pieceAt(8));\n      Console.WriteLine();\n    }\n\n    static string pieceAt(int boardPosition)\n    {\n      if (GameBoard[boardPosition] == Unplayed)\n        return (boardPosition + 1).ToString();  \n      return playerToken(GameBoard[boardPosition]);\n    }\n\n    private static bool playAgain()\n    {\n      Console.WriteLine(\"\\nDo you want to play again?\");\n      return Console.ReadKey(false).Key == ConsoleKey.Y;\n    }\n  }\n\n}\n"}
{"id": 42934, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n"}
{"id": 42935, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n"}
{"id": 42936, "name": "DNS query", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n"}
{"id": 42937, "name": "Seven-sided dice from five-sided dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "C#": "using System;\n\npublic class SevenSidedDice\n{\n    Random random = new Random();\n\t\t\n        static void Main(string[] args)\n\t\t{\n\t\t\tSevenSidedDice sevenDice = new SevenSidedDice();\n\t\t\tConsole.WriteLine(\"Random number from 1 to 7: \"+ sevenDice.seven());\n            Console.Read();\n\t\t}\n\t\t\n\t\tint seven()\n\t\t{\n\t\t\tint v=21;\n\t\t\twhile(v>20)\n\t\t\t\tv=five()+five()*5-6;\n\t\t\treturn 1+v%7;\n\t\t}\n\t\t\n\t\tint five()\n\t\t{\n        return 1 + random.Next(5);\n\t\t}\n}\n"}
{"id": 42938, "name": "Magnanimous numbers", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n", "C#": "using System; using static System.Console;\n\nclass Program {\n\n  static bool[] np; \n\n  static void ms(long lmt) { \n    np = new bool[lmt]; np[0] = np[1] = true;\n    for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])\n        for (long k = n * n; k < lmt; k += n) np[k] = true; }\n\n  static bool is_Mag(long n) { long res, rem;\n    for (long p = 10; n >= p; p *= 10) {\n      res = Math.DivRem (n, p, out rem);\n      if (np[res + rem]) return false; } return true; }\n\n  static void Main(string[] args) { ms(100_009); string mn;\n    WriteLine(\"First 45{0}\", mn = \" magnanimous numbers:\");\n    for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {\n      if (c++ < 45 || (c > 240 && c <= 250) || c > 390)\n        Write(c <= 45 ? \"{0,4} \" : \"{0,8:n0} \", l);\n      if (c < 45 && c % 15 == 0) WriteLine();\n      if (c == 240) WriteLine (\"\\n\\n241st through 250th{0}\", mn);\n      if (c == 390) WriteLine (\"\\n\\n391st through 400th{0}\", mn); } }\n}\n"}
{"id": 42939, "name": "Create a two-dimensional array at runtime", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 42940, "name": "Create a two-dimensional array at runtime", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 42941, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n"}
{"id": 42942, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n"}
{"id": 42943, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n"}
{"id": 42944, "name": "Pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n", "C#": "using System;\nusing System.Numerics;\n\nnamespace PiCalc {\n    internal class Program {\n        private readonly BigInteger FOUR = new BigInteger(4);\n        private readonly BigInteger SEVEN = new BigInteger(7);\n        private readonly BigInteger TEN = new BigInteger(10);\n        private readonly BigInteger THREE = new BigInteger(3);\n        private readonly BigInteger TWO = new BigInteger(2);\n\n        private BigInteger k = BigInteger.One;\n        private BigInteger l = new BigInteger(3);\n        private BigInteger n = new BigInteger(3);\n        private BigInteger q = BigInteger.One;\n        private BigInteger r = BigInteger.Zero;\n        private BigInteger t = BigInteger.One;\n\n        public void CalcPiDigits() {\n            BigInteger nn, nr;\n            bool first = true;\n            while (true) {\n                if ((FOUR*q + r - t).CompareTo(n*t) == -1) {\n                    Console.Write(n);\n                    if (first) {\n                        Console.Write(\".\");\n                        first = false;\n                    }\n                    nr = TEN*(r - (n*t));\n                    n = TEN*(THREE*q + r)/t - (TEN*n);\n                    q *= TEN;\n                    r = nr;\n                } else {\n                    nr = (TWO*q + r)*l;\n                    nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);\n                    q *= k;\n                    t *= l;\n                    l += TWO;\n                    k += BigInteger.One;\n                    n = nn;\n                    r = nr;\n                }\n            }\n        }\n\n        private static void Main(string[] args) {\n            new Program().CalcPiDigits();\n        }\n    }\n}\n"}
{"id": 42945, "name": "Y combinator", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n", "C#": "using System;\n\nstatic class YCombinator<T, TResult>\n{\n    \n    private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);\n\n    public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =\n        f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));\n}\n\nstatic class Program\n{\n    static void Main()\n    {\n        var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));\n        var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));\n\n        Console.WriteLine(fac(10));\n        Console.WriteLine(fib(10));\n    }\n}\n"}
{"id": 42946, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "C#": "using System.Linq; class Program { static void Main() {\n    int a, b, c, d, e, f, g; int[] h = new int[g = 1000];\n    for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)\n        for (d = a, e = b - d, f = h[b]; e <= b; e++)\n            if (f == h[d--]) { h[c] = e; break; }\n    void sho(int i) { System.Console.WriteLine(string.Join(\" \",\n        h.Skip(i).Take(10))); } sho(0); sho(990); } }\n"}
{"id": 42947, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "C#": "using System.Linq; class Program { static void Main() {\n    int a, b, c, d, e, f, g; int[] h = new int[g = 1000];\n    for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)\n        for (d = a, e = b - d, f = h[b]; e <= b; e++)\n            if (f == h[d--]) { h[c] = e; break; }\n    void sho(int i) { System.Console.WriteLine(string.Join(\" \",\n        h.Skip(i).Take(10))); } sho(0); sho(990); } }\n"}
{"id": 42948, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n"}
{"id": 42949, "name": "Dragon curve", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n"}
{"id": 42950, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n"}
{"id": 42951, "name": "Doubly-linked list_Element insertion", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n"}
{"id": 42952, "name": "Smarandache prime-digital sequence", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n"}
{"id": 42953, "name": "Quickselect algorithm", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 42954, "name": "Non-decimal radices_Convert", "Python": "i = int('1a',16)  \n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n"}
{"id": 42955, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n"}
{"id": 42956, "name": "Main step of GOST 28147-89", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n"}
{"id": 42957, "name": "Main step of GOST 28147-89", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n"}
{"id": 42958, "name": "State name puzzle", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n"}
{"id": 42959, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 42960, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 42961, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 42962, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n"}
{"id": 42963, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 42964, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 42965, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n"}
{"id": 42966, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 42967, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 42968, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 42969, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 42970, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 42971, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 42972, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 42973, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 42974, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 42975, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 42976, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 42977, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 42978, "name": "Mertens function", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n"}
{"id": 42979, "name": "Order by pair comparisons", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n"}
{"id": 42980, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42981, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 42982, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 42983, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 42984, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 42985, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 42986, "name": "Snake", "Python": "from __future__ import annotations\n\nimport itertools\nimport random\n\nfrom enum import Enum\n\nfrom typing import Any\nfrom typing import Tuple\n\nimport pygame as pg\n\nfrom pygame import Color\nfrom pygame import Rect\n\nfrom pygame.surface import Surface\n\nfrom pygame.sprite import AbstractGroup\nfrom pygame.sprite import Group\nfrom pygame.sprite import RenderUpdates\nfrom pygame.sprite import Sprite\n\n\nclass Direction(Enum):\n    UP = (0, -1)\n    DOWN = (0, 1)\n    LEFT = (-1, 0)\n    RIGHT = (1, 0)\n\n    def opposite(self, other: Direction):\n        return (self[0] + other[0], self[1] + other[1]) == (0, 0)\n\n    def __getitem__(self, i: int):\n        return self.value[i]\n\n\nclass SnakeHead(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        facing: Direction,\n        bounds: Rect,\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"aquamarine4\"))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n        self.facing = facing\n        self.size = size\n        self.speed = size\n        self.bounds = bounds\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        \n        self.rect.move_ip(\n            (\n                self.facing[0] * self.speed,\n                self.facing[1] * self.speed,\n            )\n        )\n\n        \n        if self.rect.right > self.bounds.right:\n            self.rect.left = 0\n        elif self.rect.left < 0:\n            self.rect.right = self.bounds.right\n\n        if self.rect.bottom > self.bounds.bottom:\n            self.rect.top = 0\n        elif self.rect.top < 0:\n            self.rect.bottom = self.bounds.bottom\n\n    def change_direction(self, direction: Direction):\n        if not self.facing == direction and not direction.opposite(self.facing):\n            self.facing = direction\n\n\nclass SnakeBody(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        colour: str = \"white\",\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(colour))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n\n\nclass Snake(RenderUpdates):\n    def __init__(self, game: Game) -> None:\n        self.segment_size = game.segment_size\n        self.colours = itertools.cycle([\"aquamarine1\", \"aquamarine3\"])\n\n        self.head = SnakeHead(\n            size=self.segment_size,\n            position=game.rect.center,\n            facing=Direction.RIGHT,\n            bounds=game.rect,\n        )\n\n        neck = [\n            SnakeBody(\n                size=self.segment_size,\n                position=game.rect.center,\n                colour=next(self.colours),\n            )\n            for _ in range(2)\n        ]\n\n        super().__init__(*[self.head, *neck])\n\n        self.body = Group()\n        self.tail = neck[-1]\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        self.head.update()\n\n        \n        segments = self.sprites()\n        for i in range(len(segments) - 1, 0, -1):\n            \n            segments[i].rect.center = segments[i - 1].rect.center\n\n    def change_direction(self, direction: Direction):\n        self.head.change_direction(direction)\n\n    def grow(self):\n        tail = SnakeBody(\n            size=self.segment_size,\n            position=self.tail.rect.center,\n            colour=next(self.colours),\n        )\n        self.tail = tail\n        self.add(self.tail)\n        self.body.add(self.tail)\n\n\nclass SnakeFood(Sprite):\n    def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None:\n        super().__init__(*groups)\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"red\"))\n        self.rect = self.image.get_rect()\n\n        self.rect.topleft = (\n            random.randint(0, game.rect.width),\n            random.randint(0, game.rect.height),\n        )\n\n        self.rect.clamp_ip(game.rect)\n\n        \n        \n        while pg.sprite.spritecollideany(self, game.snake):\n            self.rect.topleft = (\n                random.randint(0, game.rect.width),\n                random.randint(0, game.rect.height),\n            )\n\n            self.rect.clamp_ip(game.rect)\n\n\nclass Game:\n    def __init__(self) -> None:\n        self.rect = Rect(0, 0, 640, 480)\n        self.background = Surface(self.rect.size)\n        self.background.fill(Color(\"black\"))\n\n        self.score = 0\n        self.framerate = 16\n\n        self.segment_size = 10\n        self.snake = Snake(self)\n        self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size))\n\n        pg.init()\n\n    def _init_display(self) -> Surface:\n        bestdepth = pg.display.mode_ok(self.rect.size, 0, 32)\n        screen = pg.display.set_mode(self.rect.size, 0, bestdepth)\n\n        pg.display.set_caption(\"Snake\")\n        pg.mouse.set_visible(False)\n\n        screen.blit(self.background, (0, 0))\n        pg.display.flip()\n\n        return screen\n\n    def draw(self, screen: Surface):\n        dirty = self.snake.draw(screen)\n        pg.display.update(dirty)\n\n        dirty = self.food_group.draw(screen)\n        pg.display.update(dirty)\n\n    def update(self, screen):\n        self.food_group.clear(screen, self.background)\n        self.food_group.update()\n        self.snake.clear(screen, self.background)\n        self.snake.update()\n\n    def main(self) -> int:\n        screen = self._init_display()\n        clock = pg.time.Clock()\n\n        while self.snake.head.alive():\n            for event in pg.event.get():\n                if event.type == pg.QUIT or (\n                    event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q)\n                ):\n                    return self.score\n\n            \n            keystate = pg.key.get_pressed()\n\n            if keystate[pg.K_RIGHT]:\n                self.snake.change_direction(Direction.RIGHT)\n            elif keystate[pg.K_LEFT]:\n                self.snake.change_direction(Direction.LEFT)\n            elif keystate[pg.K_UP]:\n                self.snake.change_direction(Direction.UP)\n            elif keystate[pg.K_DOWN]:\n                self.snake.change_direction(Direction.DOWN)\n\n            \n            self.update(screen)\n\n            \n            for food in pg.sprite.spritecollide(\n                self.snake.head, self.food_group, dokill=False\n            ):\n                food.kill()\n                self.snake.grow()\n                self.score += 1\n\n                \n                if self.score % 5 == 0:\n                    self.framerate += 1\n\n                self.food_group.add(SnakeFood(self, self.segment_size))\n\n            \n            if pg.sprite.spritecollideany(self.snake.head, self.snake.body):\n                self.snake.head.kill()\n\n            self.draw(screen)\n            clock.tick(self.framerate)\n\n        return self.score\n\n\nif __name__ == \"__main__\":\n    game = Game()\n    score = game.main()\n    print(score)\n", "C": "\n\n\n\n\n\n\n\n\nchar nonblocking_getch();\nvoid positional_putch(int x, int y, char ch);\nvoid millisecond_sleep(int n);\nvoid init_screen();\nvoid update_screen();\nvoid close_screen();\n\n\n\n#ifdef __linux__\n#define _POSIX_C_SOURCE 200809L\n#include <time.h> \n#include <ncurses.h> \nchar nonblocking_getch() { return getch(); }\nvoid positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }\nvoid millisecond_sleep(int n) { \n\tstruct timespec t = { 0, n * 1000000 };\n\tnanosleep(&t, 0);\n\t\n}\nvoid update_screen() { refresh(); }\nvoid init_screen() {\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\tnodelay(stdscr, TRUE);\n}\nvoid close_screen() { endwin(); }\n#endif\n\n\n#ifdef _WIN32\n#error \"not implemented\"\n#endif\n\n\n#include <time.h> \n#include <stdlib.h> \n\n#define w 80\n#define h 40\n\nint board[w * h];\nint head;\nenum Dir { N, E, S, W } dir;\nint quit;\n\nenum State { SPACE=0, FOOD=1, BORDER=2 };\n\n\n\nvoid age() {\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tif(board[i] < 0)\n\t\t\t++board[i];\n}\n\n\nvoid plant() {\n\tint r;\n\tdo\n\t\tr = rand() % (w * h);\n\twhile(board[r] != SPACE);\n\tboard[r] = FOOD;\n}\n\n\nvoid start(void) {\n        int i;\n\tfor(i = 0; i < w; ++i)\n\t\tboard[i] = board[i + (h - 1) * w] = BORDER;\n\tfor(i = 0; i < h; ++i)\n\t\tboard[i * w] = board[i * w + w - 1] = BORDER;\n\thead = w * (h - 1 - h % 2) / 2; \n\tboard[head] = -5;\n\tdir = N;\n\tquit = 0;\n\tsrand(time(0));\n\tplant();\n}\n\nvoid step() {\n\tint len = board[head];\n\tswitch(dir) {\n\t\tcase N: head -= w; break;\n\t\tcase S: head += w; break;\n\t\tcase W: --head; break;\n\t\tcase E: ++head; break;\n\t}\n\tswitch(board[head]) {\n\t\tcase SPACE:\n\t\t\tboard[head] = len - 1; \n\t\t\tage();\n\t\t\tbreak;\n\t\tcase FOOD:\n\t\t\tboard[head] = len - 1;\n\t\t\tplant();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tquit = 1;\n\t}\n}\n\nvoid show() {\n\tconst char * symbol = \" @.\";\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tpositional_putch(i / w, i % w,\n\t\t\tboard[i] < 0 ? '#' : symbol[board[i]]);\n\tupdate_screen();\n}\n\nint main (int argc, char * argv[]) {\n\tinit_screen();\n\tstart();\n\tdo {\n\t\tshow();\n\t\tswitch(nonblocking_getch()) {\n\t\t\tcase 'i': dir = N; break;\n\t\t\tcase 'j': dir = W; break;\n\t\t\tcase 'k': dir = S; break;\n\t\t\tcase 'l': dir = E; break;\n\t\t\tcase 'q': quit = 1; break;\n\t\t}\n\t\tstep();\n\t\tmillisecond_sleep(100); \n\t\t\n\t}\n\twhile(!quit);\n\tmillisecond_sleep(999);\n\tclose_screen();\n\treturn 0;\n}\n"}
{"id": 42987, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 42988, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 42989, "name": "Legendre prime counting function", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 42990, "name": "Use another language to call a function", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n"}
{"id": 42991, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n"}
{"id": 42992, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 42993, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 42994, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n"}
{"id": 42995, "name": "Unprimeable numbers", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n"}
{"id": 42996, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 42997, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 42998, "name": "Chernick's Carmichael numbers", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 42999, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43000, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43001, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43002, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43003, "name": "Sequence of primorial primes", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n"}
{"id": 43004, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 43005, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 43006, "name": "Dining philosophers", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n"}
{"id": 43007, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 43008, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 43009, "name": "Logistic curve fitting in epidemiology", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n"}
{"id": 43010, "name": "Sorting algorithms_Strand sort", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n"}
{"id": 43011, "name": "Additive primes", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n"}
{"id": 43012, "name": "Inverted syntax", "Python": "x = truevalue if condition else falsevalue\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n"}
{"id": 43013, "name": "Inverted syntax", "Python": "x = truevalue if condition else falsevalue\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n"}
{"id": 43014, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 43015, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 43016, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n"}
{"id": 43017, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 43018, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 43019, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43020, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43021, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n"}
{"id": 43022, "name": "Sutherland-Hodgman polygon clipping", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n"}
{"id": 43023, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 43024, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 43025, "name": "Spiral matrix", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 43026, "name": "Optional parameters", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n"}
{"id": 43027, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 43028, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 43029, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n"}
{"id": 43030, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 43031, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 43032, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 43033, "name": "Faulhaber's triangle", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n"}
{"id": 43034, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43035, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43036, "name": "Word wheel", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n"}
{"id": 43037, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n"}
{"id": 43038, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43039, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 43040, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 43041, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 43042, "name": "Primes - allocate descendants to their ancestors", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n"}
{"id": 43043, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 43044, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 43045, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n"}
{"id": 43046, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 43047, "name": "XML_Output", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n"}
{"id": 43048, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 43049, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 43050, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n"}
{"id": 43051, "name": "Guess the number_With feedback (player)", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n"}
{"id": 43052, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n"}
{"id": 43053, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43054, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43055, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43056, "name": "Fractal tree", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n"}
{"id": 43057, "name": "Colour pinstripe_Display", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n"}
{"id": 43058, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 43059, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 43060, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n"}
{"id": 43061, "name": "Animate a pendulum", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 43062, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 43063, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 43064, "name": "Create a file on magnetic tape", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n"}
{"id": 43065, "name": "Sorting algorithms_Heapsort", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 43066, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n"}
{"id": 43067, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 43068, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43069, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n"}
{"id": 43070, "name": "Merge and aggregate datasets", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n"}
{"id": 43071, "name": "Euler method", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n"}
{"id": 43072, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 43073, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43074, "name": "JortSort", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n"}
{"id": 43075, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n"}
{"id": 43076, "name": "Combinations and permutations", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n"}
{"id": 43077, "name": "Sort numbers lexicographically", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n"}
{"id": 43078, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n"}
{"id": 43079, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43080, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 43081, "name": "Doubly-linked list_Definition", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n"}
{"id": 43082, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 43083, "name": "Permutation test", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n"}
{"id": 43084, "name": "Möbius function", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n"}
{"id": 43085, "name": "Increment a numerical string", "Python": "next = str(int('123') + 1)\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n"}
{"id": 43086, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 43087, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 43088, "name": "Sorting algorithms_Permutation sort", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n"}
{"id": 43089, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43090, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43091, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43092, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 43093, "name": "Tokenize a string with escaping", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n"}
{"id": 43094, "name": "Sexy primes", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef unsigned char bool;\n\nvoid sieve(bool *c, int limit) {\n    int i, p = 3, p2;\n    \n    c[0] = TRUE;\n    c[1] = TRUE;\n    \n    for (;;) {\n        p2 = p * p;\n        if (p2 >= limit) {\n            break;\n        }\n        for (i = p2; i < limit; i += 2*p) {\n            c[i] = TRUE;\n        }\n        for (;;) {\n            p += 2;\n            if (!c[p]) {\n                break;\n            }\n        }\n    }\n}\n\nvoid printHelper(const char *cat, int len, int lim, int n) {\n    const char *sp = strcmp(cat, \"unsexy primes\") ? \"sexy prime \" : \"\";\n    const char *verb = (len == 1) ? \"is\" : \"are\";\n    printf(\"Number of %s%s less than %'d = %'d\\n\", sp, cat, lim, len);\n    printf(\"The last %d %s:\\n\", n, verb);\n}\n\nvoid printArray(int *a, int len) {\n    int i;\n    printf(\"[\");\n    for (i = 0; i < len; ++i) printf(\"%d \", a[i]);\n    printf(\"\\b]\");\n}\n\nint main() {\n    int i, ix, n, lim = 1000035;\n    int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;\n    int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;\n    int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;\n    int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];\n    int last_un[10];\n    bool *sv = calloc(lim - 1, sizeof(bool)); \n    setlocale(LC_NUMERIC, \"\");\n    sieve(sv, lim);\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            unsexy++;\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pairs++;\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            trips++;\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            quads++;\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            quins++;\n        }\n    }\n    if (pairs < lpr) lpr = pairs;\n    if (trips < ltr) ltr = trips;\n    if (quads < lqd) lqd = quads;\n    if (quins < lqn) lqn = quins;\n    if (unsexy < lun) lun = unsexy;\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            un++;\n            if (un > unsexy - lun) {\n                last_un[un + lun - 1 - unsexy] = i;\n            }\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pr++;\n            if (pr > pairs - lpr) {\n                ix = pr + lpr - 1 - pairs;\n                last_pr[ix][0] = i; last_pr[ix][1] = i + 6;\n            }\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            tr++;\n            if (tr > trips - ltr) {\n                ix = tr + ltr - 1 - trips;\n                last_tr[ix][0] = i; last_tr[ix][1] = i + 6;\n                last_tr[ix][2] = i + 12;\n            }\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            qd++;\n            if (qd > quads - lqd) {\n                ix = qd + lqd - 1 - quads;\n                last_qd[ix][0] = i; last_qd[ix][1] = i + 6;\n                last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;\n            }\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            qn++;\n            if (qn > quins - lqn) {\n                ix = qn + lqn - 1 - quins;\n                last_qn[ix][0] = i; last_qn[ix][1] = i + 6;\n                last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;\n                last_qn[ix][4] = i + 24;\n            }\n        }\n    }\n\n    printHelper(\"pairs\", pairs, lim, lpr);\n    printf(\"  [\");\n    for (i = 0; i < lpr; ++i) {\n        printArray(last_pr[i], 2);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"triplets\", trips, lim, ltr);\n    printf(\"  [\");\n    for (i = 0; i < ltr; ++i) {\n        printArray(last_tr[i], 3);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quadruplets\", quads, lim, lqd);\n    printf(\"  [\");\n    for (i = 0; i < lqd; ++i) {\n        printArray(last_qd[i], 4);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quintuplets\", quins, lim, lqn);\n    printf(\"  [\");\n    for (i = 0; i < lqn; ++i) {\n        printArray(last_qn[i], 5);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"unsexy primes\", unsexy, lim, lun);\n    printf(\"  [\");\n    printArray(last_un, lun);\n    printf(\"\\b]\\n\");\n    free(sv);\n    return 0;\n}\n"}
{"id": 43095, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n"}
{"id": 43096, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n"}
{"id": 43097, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n"}
{"id": 43098, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n"}
{"id": 43099, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n"}
{"id": 43100, "name": "Singly-linked list_Traversal", "Python": "for node in lst:\n    print node.value\n", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n"}
{"id": 43101, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43102, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n"}
{"id": 43103, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n"}
{"id": 43104, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n"}
{"id": 43105, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"}
{"id": 43106, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"}
{"id": 43107, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n"}
{"id": 43108, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n"}
{"id": 43109, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 43110, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 43111, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "C": "#include <stdio.h>\n\nint main() {\n  const char *extra = \"little\";\n  printf(\"Mary had a %s lamb.\\n\", extra);\n  return 0;\n}\n"}
{"id": 43112, "name": "Sorting algorithms_Patience sort", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint* patienceSort(int* arr,int size){\n\tint decks[size][size],i,j,min,pickedRow;\n\t\n\tint *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){\n\t\t\t\tdecks[j][count[j]] = arr[i];\n\t\t\t\tcount[j]++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmin = decks[0][count[0]-1];\n\tpickedRow = 0;\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]>0 && decks[j][count[j]-1]<min){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t}\n\t\t}\n\t\tsortedArr[i] = min;\n\t\tcount[pickedRow]--;\n\t\t\n\t\tfor(j=0;j<size;j++)\n\t\t\tif(count[j]>0){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\t\n\tfree(count);\n\tfree(decks);\n\t\n\treturn sortedArr;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr, *sortedArr, i;\n\t\n\tif(argC==0)\n\t\tprintf(\"Usage : %s <integers to be sorted separated by space>\");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i<=argC;i++)\n\t\t\tarr[i-1] = atoi(argV[i]);\n\t\t\n\t\tsortedArr = patienceSort(arr,argC-1);\n\t\t\n\t\tfor(i=0;i<argC-1;i++)\n\t\t\tprintf(\"%d \",sortedArr[i]);\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 43113, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 43114, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 43115, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 43116, "name": "Tau number", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n", "C": "#include <stdio.h>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    unsigned int p;\n\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int count = 0;\n    unsigned int n;\n\n    printf(\"The first %d tau numbers are:\\n\", limit);\n    for (n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            printf(\"%6d\", n);\n            ++count;\n            if (count % 10 == 0) {\n                printf(\"\\n\");\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43117, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n"}
{"id": 43118, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n"}
{"id": 43119, "name": "Partition function P", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n", "C": "#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <gmp.h>\n\nmpz_t* partition(uint64_t n) {\n\tmpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));\n\tmpz_init_set_ui(pn[0], 1);\n\tmpz_init_set_ui(pn[1], 1);\n\tfor (uint64_t i = 2; i < n + 2; i ++) {\n\t\tmpz_init(pn[i]);\n\t\tfor (uint64_t k = 1, penta; ; k++) {\n\t\t\tpenta = k * (3 * k - 1) >> 1;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t\tpenta += k;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t}\n\t}\n\tmpz_t *tmp = &pn[n + 1];\n\tfor (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);\n\tfree(pn);\n\treturn tmp;\n}\n\nint main(int argc, char const *argv[]) {\n\tclock_t start = clock();\n\tmpz_t *p = partition(6666);\n\tgmp_printf(\"%Zd\\n\", p);\n\tprintf(\"Elapsed time: %.04f seconds\\n\",\n\t\t(double)(clock() - start) / (double)CLOCKS_PER_SEC);\n\treturn 0;\n}\n"}
{"id": 43120, "name": "Wireworld", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n", "C": "\n#define ANIMATE_VT100_POSIX\n#include <stdio.h>\n#include <string.h>\n#ifdef ANIMATE_VT100_POSIX\n#include <time.h>\n#endif\n\nchar world_7x14[2][512] = {\n  {\n    \"+-----------+\\n\"\n    \"|tH.........|\\n\"\n    \"|.   .      |\\n\"\n    \"|   ...     |\\n\"\n    \"|.   .      |\\n\"\n    \"|Ht.. ......|\\n\"\n    \"+-----------+\\n\"\n  }\n};\n\nvoid next_world(const char *in, char *out, int w, int h)\n{\n  int i;\n\n  for (i = 0; i < w*h; i++) {\n    switch (in[i]) {\n    case ' ': out[i] = ' '; break;\n    case 't': out[i] = '.'; break;\n    case 'H': out[i] = 't'; break;\n    case '.': {\n      int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') +\n               (in[i-1]   == 'H')                    + (in[i+1]   == 'H') +\n               (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H');\n      out[i] = (hc == 1 || hc == 2) ? 'H' : '.';\n      break;\n    }\n    default:\n      out[i] = in[i];\n    }\n  }\n  out[i] = in[i];\n}\n\nint main()\n{\n  int f;\n\n  for (f = 0; ; f = 1 - f) {\n    puts(world_7x14[f]);\n    next_world(world_7x14[f], world_7x14[1-f], 14, 7);\n#ifdef ANIMATE_VT100_POSIX\n    printf(\"\\x1b[%dA\", 8);\n    printf(\"\\x1b[%dD\", 14);\n    {\n      static const struct timespec ts = { 0, 100000000 };\n      nanosleep(&ts, 0);\n    }\n#endif\n  }\n\n  return 0;\n}\n"}
{"id": 43121, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec;\ntypedef struct { int n; vec* v; } polygon_t, *polygon;\n\n#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}\n#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }\nBIN_V(sub, a.x - b.x, a.y - b.y);\nBIN_V(add, a.x + b.x, a.y + b.y);\nBIN_S(dot, a.x * b.x + a.y * b.y);\nBIN_S(cross, a.x * b.y - a.y * b.x);\n\n\nvec vmadd(vec a, double s, vec b)\n{\n\tvec c;\n\tc.x = a.x + s * b.x;\n\tc.y = a.y + s * b.y;\n\treturn c;\n}\n\n\nint intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)\n{\n\tvec dx = vsub(x1, x0), dy = vsub(y1, y0);\n\tdouble d = vcross(dy, dx), a;\n\tif (!d) return 0; \n\n\ta = (vcross(x0, dx) - vcross(y0, dx)) / d;\n\tif (sect)\n\t\t*sect = vmadd(y0, a, dy);\n\n\tif (a < -tol || a > 1 + tol) return -1;\n\tif (a < tol || a > 1 - tol) return 0;\n\n\ta = (vcross(x0, dy) - vcross(y0, dy)) / d;\n\tif (a < 0 || a > 1) return -1;\n\n\treturn 1;\n}\n\n\ndouble dist(vec x, vec y0, vec y1, double tol)\n{\n\tvec dy = vsub(y1, y0);\n\tvec x1, s;\n\tint r;\n\n\tx1.x = x.x + dy.y; x1.y = x.y - dy.x;\n\tr = intersect(x, x1, y0, y1, tol, &s);\n\tif (r == -1) return HUGE_VAL;\n\ts = vsub(s, x);\n\treturn sqrt(vdot(s, s));\n}\n\n#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)\n\nint inside(vec v, polygon p, double tol)\n{\n\t\n\tint i, k, crosses, intersectResult;\n\tvec *pv;\n\tdouble min_x, max_x, min_y, max_y;\n\n\tfor (i = 0; i < p->n; i++) {\n\t\tk = (i + 1) % p->n;\n\t\tmin_x = dist(v, p->v[i], p->v[k], tol);\n\t\tif (min_x < tol) return 0;\n\t}\n\n\tmin_x = max_x = p->v[0].x;\n\tmin_y = max_y = p->v[1].y;\n\n\t\n\tfor_v(i, pv, p) {\n\t\tif (pv->x > max_x) max_x = pv->x;\n\t\tif (pv->x < min_x) min_x = pv->x;\n\t\tif (pv->y > max_y) max_y = pv->y;\n\t\tif (pv->y < min_y) min_y = pv->y;\n\t}\n\tif (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)\n\t\treturn -1;\n\n\tmax_x -= min_x; max_x *= 2;\n\tmax_y -= min_y; max_y *= 2;\n\tmax_x += max_y;\n\n\tvec e;\n\twhile (1) {\n\t\tcrosses = 0;\n\t\t\n\t\te.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\t\te.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\n\t\tfor (i = 0; i < p->n; i++) {\n\t\t\tk = (i + 1) % p->n;\n\t\t\tintersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);\n\n\t\t\t\n\t\t\tif (!intersectResult) break;\n\n\t\t\tif (intersectResult == 1) crosses++;\n\t\t}\n\t\tif (i == p->n) break;\n\t}\n\treturn (crosses & 1) ? 1 : -1;\n}\n\nint main()\n{\n\tvec vsq[] = {\t{0,0}, {10,0}, {10,10}, {0,10},\n\t\t\t{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};\n\n\tpolygon_t sq = { 4, vsq }, \n\t\tsq_hole = { 8, vsq }; \n\n\tvec c = { 10, 5 }; \n\tvec d = { 5, 5 };\n\n\tprintf(\"%d\\n\", inside(c, &sq, 1e-10));\n\tprintf(\"%d\\n\", inside(c, &sq_hole, 1e-10));\n\n\tprintf(\"%d\\n\", inside(d, &sq, 1e-10));\t\n\tprintf(\"%d\\n\", inside(d, &sq_hole, 1e-10));  \n\n\treturn 0;\n}\n"}
{"id": 43122, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n"}
{"id": 43123, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n"}
{"id": 43124, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint match(const char *s, const char *p, int overlap)\n{\n        int c = 0, l = strlen(p);\n\n        while (*s != '\\0') {\n                if (strncmp(s++, p, l)) continue;\n                if (!overlap) s += l - 1;\n                c++;\n        }\n        return c;\n}\n\nint main()\n{\n        printf(\"%d\\n\", match(\"the three truths\", \"th\", 0));\n        printf(\"overlap:%d\\n\", match(\"abababababa\", \"aba\", 1));\n        printf(\"not:    %d\\n\", match(\"abababababa\", \"aba\", 0));\n        return 0;\n}\n"}
{"id": 43125, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43126, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43127, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43128, "name": "String comparison", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n", "C": "\nif (strcmp(a,b)) action_on_equality();\n"}
{"id": 43129, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n"}
{"id": 43130, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n"}
{"id": 43131, "name": "Thiele's interpolation formula", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define N 32\n#define N2 (N * (N - 1) / 2)\n#define STEP .05\n\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\n\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\n\n\n\ndouble rho(double *x, double *y, double *r, int i, int n)\n{\n\tif (n < 0) return 0;\n\tif (!n) return y[i];\n\n\tint idx = (N - 1 - n) * (N - n) / 2 + i;\n\tif (r[idx] != r[idx]) \n\t\tr[idx] = (x[i] - x[i + n])\n\t\t\t/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n\t\t\t+ rho(x, y, r, i + 1, n - 2);\n\treturn r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, int n)\n{\n\tif (n > N - 1) return 1;\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n\t\t+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\n#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)\n#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)\n#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\txval[i] = i * STEP;\n\t\tt_sin[i] = sin(xval[i]);\n\t\tt_cos[i] = cos(xval[i]);\n\t\tt_tan[i] = t_sin[i] / t_cos[i];\n\t}\n\tfor (i = 0; i < N2; i++)\n\t\t\n\t\tr_sin[i] = r_cos[i] = r_tan[i] = 0/0.;\n\n\tprintf(\"%16.14f\\n\", 6 * i_sin(.5));\n\tprintf(\"%16.14f\\n\", 3 * i_cos(.5));\n\tprintf(\"%16.14f\\n\", 4 * i_tan(1.));\n\treturn 0;\n}\n"}
{"id": 43132, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n"}
{"id": 43133, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n"}
{"id": 43134, "name": "Angles (geometric), normalization and conversion", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n", "C": "#define PI 3.141592653589793\n#define TWO_PI 6.283185307179586\n\ndouble normalize2deg(double a) {\n  while (a < 0) a += 360;\n  while (a >= 360) a -= 360;\n  return a;\n}\ndouble normalize2grad(double a) {\n  while (a < 0) a += 400;\n  while (a >= 400) a -= 400;\n  return a;\n}\ndouble normalize2mil(double a) {\n  while (a < 0) a += 6400;\n  while (a >= 6400) a -= 6400;\n  return a;\n}\ndouble normalize2rad(double a) {\n  while (a < 0) a += TWO_PI;\n  while (a >= TWO_PI) a -= TWO_PI;\n  return a;\n}\n\ndouble deg2grad(double a) {return a * 10 / 9;}\ndouble deg2mil(double a) {return a * 160 / 9;}\ndouble deg2rad(double a) {return a * PI / 180;}\n\ndouble grad2deg(double a) {return a * 9 / 10;}\ndouble grad2mil(double a) {return a * 16;}\ndouble grad2rad(double a) {return a * PI / 200;}\n\ndouble mil2deg(double a) {return a * 9 / 160;}\ndouble mil2grad(double a) {return a / 16;}\ndouble mil2rad(double a) {return a * PI / 3200;}\n\ndouble rad2deg(double a) {return a * 180 / PI;}\ndouble rad2grad(double a) {return a * 200 / PI;}\ndouble rad2mil(double a) {return a * 3200 / PI;}\n"}
{"id": 43135, "name": "Find common directory path", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n", "C": "#include <stdio.h>\n\nint common_len(const char *const *names, int n, char sep)\n{\n\tint i, pos;\n\tfor (pos = 0; ; pos++) {\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tif (names[i][pos] != '\\0' &&\n\t\t\t\t\tnames[i][pos] == names[0][pos])\n\t\t\t\tcontinue;\n\n\t\t\t\n\t\t\twhile (pos > 0 && names[0][--pos] != sep);\n\t\t\treturn pos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint main()\n{\n\tconst char *names[] = {\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t};\n\tint len = common_len(names, sizeof(names) / sizeof(const char*), '/');\n\n\tif (!len) printf(\"No common path\\n\");\n\telse      printf(\"Common path: %.*s\\n\", len, names[0]);\n\n\treturn 0;\n}\n"}
{"id": 43136, "name": "Verify distribution uniformity_Naive", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\ninline int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n\ninline int rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\n\nint check(int (*gen)(), int n, int cnt, double delta) \n{\n\tint i = cnt, *bins = calloc(sizeof(int), n);\n\tdouble ratio;\n\twhile (i--) bins[gen() - 1]++;\n\tfor (i = 0; i < n; i++) {\n\t\tratio = bins[i] * n / (double)cnt - 1;\n\t\tif (ratio > -delta && ratio < delta) continue;\n\n\t\tprintf(\"bin %d out of range: %d (%g%% vs %g%%), \",\n\t\t\ti + 1, bins[i], ratio * 100, delta * 100);\n\t\tbreak;\n\t}\n\tfree(bins);\n\treturn i == n;\n}\n\nint main()\n{\n\tint cnt = 1;\n\twhile ((cnt *= 10) <= 1000000) {\n\t\tprintf(\"Count = %d: \", cnt);\n\t\tprintf(check(rand5_7, 7, cnt, 0.03) ? \"flat\\n\" : \"NOT flat\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43137, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n"}
{"id": 43138, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n"}
{"id": 43139, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n"}
{"id": 43140, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n"}
{"id": 43141, "name": "Memory allocation", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n", "C": "#include <stdlib.h>\n\n\n#define SIZEOF_MEMB (sizeof(int))\n#define NMEMB 100\n\nint main()\n{\n  int *ints = malloc(SIZEOF_MEMB*NMEMB);\n  \n  ints = realloc(ints, sizeof(int)*(NMEMB+1));\n  \n  int *int2 = calloc(NMEMB, SIZEOF_MEMB);\n  \n  free(ints); free(int2);\n  return 0;\n}\n"}
{"id": 43142, "name": "Tic-tac-toe", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint b[3][3]; \n\nint check_winner()\n{\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tif (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])\n\t\t\treturn b[i][0];\n\t\tif (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])\n\t\t\treturn b[0][i];\n\t}\n\tif (!b[1][1]) return 0;\n\n\tif (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];\n\tif (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];\n\n\treturn 0;\n}\n\nvoid showboard()\n{\n\tconst char *t = \"X O\";\n\tint i, j;\n\tfor (i = 0; i < 3; i++, putchar('\\n'))\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%c \", t[ b[i][j] + 1 ]);\n\tprintf(\"-----\\n\");\n}\n\n#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)\nint best_i, best_j;\nint test_move(int val, int depth)\n{\n\tint i, j, score;\n\tint best = -1, changed = 0;\n\n\tif ((score = check_winner())) return (score == val) ? 1 : -1;\n\n\tfor_ij {\n\t\tif (b[i][j]) continue;\n\n\t\tchanged = b[i][j] = val;\n\t\tscore = -test_move(-val, depth + 1);\n\t\tb[i][j] = 0;\n\n\t\tif (score <= best) continue;\n\t\tif (!depth) {\n\t\t\tbest_i = i;\n\t\t\tbest_j = j;\n\t\t}\n\t\tbest = score;\n\t}\n\n\treturn changed ? best : 0;\n}\n\nconst char* game(int user)\n{\n\tint i, j, k, move, win = 0;\n\tfor_ij b[i][j] = 0;\n\n\tprintf(\"Board postions are numbered so:\\n1 2 3\\n4 5 6\\n7 8 9\\n\");\n\tprintf(\"You have O, I have X.\\n\\n\");\n\tfor (k = 0; k < 9; k++, user = !user) {\n\t\twhile(user) {\n\t\t\tprintf(\"your move: \");\n\t\t\tif (!scanf(\"%d\", &move)) {\n\t\t\t\tscanf(\"%*s\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (--move < 0 || move >= 9) continue;\n\t\t\tif (b[i = move / 3][j = move % 3]) continue;\n\n\t\t\tb[i][j] = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (!user) {\n\t\t\tif (!k) { \n\t\t\t\tbest_i = rand() % 3;\n\t\t\t\tbest_j = rand() % 3;\n\t\t\t} else\n\t\t\t\ttest_move(-1, 0);\n\n\t\t\tb[best_i][best_j] = -1;\n\t\t\tprintf(\"My move: %d\\n\", best_i * 3 + best_j + 1);\n\t\t}\n\n\t\tshowboard();\n\t\tif ((win = check_winner())) \n\t\t\treturn win == 1 ? \"You win.\\n\\n\": \"I win.\\n\\n\";\n\t}\n\treturn \"A draw.\\n\\n\";\n}\n\nint main()\n{\n\tint first = 0;\n\twhile (1) printf(\"%s\", game(first = !first));\n\treturn 0;\n}\n"}
{"id": 43143, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n"}
{"id": 43144, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n"}
{"id": 43145, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n"}
{"id": 43146, "name": "Entropy_Narcissist", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 43147, "name": "Entropy_Narcissist", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 43148, "name": "DNS query", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n", "C": "#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\t\t\n#include <stdio.h>\t\t\n#include <stdlib.h>\t\t\n#include <string.h>\t\t\n\nint\nmain()\n{\n\tstruct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n\t\n\tmemset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;     \n\thints.ai_socktype = SOCK_DGRAM;  \n\n\t\n\terror = getaddrinfo(\"www.kame.net\", NULL, &hints, &res0);\n\tif (error) {\n\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\texit(1);\n\t}\n\n\t\n\tfor (res = res0; res; res = res->ai_next) {\n\t\t\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\n\t\tif (error) {\n\t\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\\n\", host);\n\t\t}\n\t}\n\n\t\n\tfreeaddrinfo(res0);\n\n\treturn 0;\n}\n"}
{"id": 43149, "name": "Peano curve", "Python": "import turtle as tt\nimport inspect\n\nstack = [] \ndef peano(iterations=1):\n    global stack\n\n    \n    ivan = tt.Turtle(shape = \"classic\", visible = True)\n\n\n    \n    screen = tt.Screen()\n    screen.title(\"Desenhin do Peano\")\n    screen.bgcolor(\"\n    screen.delay(0) \n    screen.setup(width=0.95, height=0.9)\n\n    \n    walk = 1\n\n    def screenlength(k):\n        \n        \n        if k != 0:\n            length = screenlength(k-1)\n            return 2*length + 1\n        else: return 0\n\n    kkkj = screenlength(iterations)\n    screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)\n    ivan.color(\"\n\n\n    \n    def step1(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n    def step2(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n\n    \n    ivan.left(90)\n    step2(iterations)\n\n    tt.done()\n\nif __name__ == \"__main__\":\n    peano(4)\n    import pylab as P \n    P.plot(stack)\n    P.show()\n", "C": "\n\n#include <graphics.h>\n#include <math.h>\n\nvoid Peano(int x, int y, int lg, int i1, int i2) {\n\n\tif (lg == 1) {\n\t\tlineto(3*x,3*y);\n\t\treturn;\n\t}\n\t\n\tlg = lg/3;\n\tPeano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2);\n\tPeano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2);\n\tPeano(x+lg, y+lg, lg, i1, 1-i2);\n\tPeano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2);\n\tPeano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2);\n\tPeano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2);\n\tPeano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2);\n\tPeano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2);\n\tPeano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2);\n}\n\nint main(void) {\n\n\tinitwindow(1000,1000,\"Peano, Peano\");\n\n\tPeano(0, 0, 1000, 0, 0); \n\t\n\tgetch();\n\tcleardevice();\n\t\n\treturn 0;\n}\n"}
{"id": 43150, "name": "Seven-sided dice from five-sided dice", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n", "C": "int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n \nint rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\nint main()\n{\n\tprintf(check(rand5, 5, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\tprintf(check(rand7, 7, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\treturn 0;\n}\n"}
{"id": 43151, "name": "Solve the no connection puzzle", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <math.h>\n\nint connections[15][2] = {\n    {0, 2}, {0, 3}, {0, 4}, \n    {1, 3}, {1, 4}, {1, 5}, \n    {6, 2}, {6, 3}, {6, 4}, \n    {7, 3}, {7, 4}, {7, 5}, \n    {2, 3}, {3, 4}, {4, 5}, \n};\n\nint pegs[8];\nint num = 0;\n\nbool valid() {\n    int i;\n    for (i = 0; i < 15; i++) {\n        if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid swap(int *a, int *b) {\n    int t = *a;\n    *a = *b;\n    *b = t;\n}\n\nvoid printSolution() {\n    printf(\"----- %d -----\\n\", num++);\n    printf(\"  %d %d\\n\",  pegs[0], pegs[1]);\n    printf(\"%d %d %d %d\\n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n    printf(\"  %d %d\\n\",  pegs[6], pegs[7]);\n    printf(\"\\n\");\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        int i;\n        for (i = le; i <= ri; i++) {\n            swap(pegs + le, pegs + i);\n            solution(le + 1, ri);\n            swap(pegs + le, pegs + i);\n        }\n    }\n}\n\nint main() {\n    int i;\n    for (i = 0; i < 8; i++) {\n        pegs[i] = i + 1;\n    }\n\n    solution(0, 8 - 1);\n    return 0;\n}\n"}
{"id": 43152, "name": "Extensible prime generator", "Python": "islice(count(7), 0, None, 2)\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#define CHUNK_BYTES (32 << 8)\n#define CHUNK_SIZE (CHUNK_BYTES << 6)\n\nint field[CHUNK_BYTES];\n#define GET(x) (field[(x)>>6] &  1<<((x)>>1&31))\n#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))\n\ntypedef unsigned uint;\ntypedef struct {\n        uint *e;\n        uint cap, len;\n} uarray;\nuarray primes, offset;\n\nvoid push(uarray *a, uint n)\n{\n        if (a->len >= a->cap) {\n                if (!(a->cap *= 2)) a->cap = 16;\n                a->e = realloc(a->e, sizeof(uint) * a->cap);\n        }\n        a->e[a->len++] = n;\n}\n\nuint low;\nvoid init(void)\n{\n        uint p, q;\n\n        unsigned char f[1<<16];\n        memset(f, 0, sizeof(f));\n        push(&primes, 2);\n        push(&offset, 0);\n        for (p = 3; p < 1<<16; p += 2) {\n                if (f[p]) continue;\n                for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;\n                push(&primes, p);\n                push(&offset, q);\n        }\n        low = 1<<16;\n}\n\nvoid sieve(void)\n{\n        uint i, p, q, hi, ptop;\n        if (!low) init();\n\n        memset(field, 0, sizeof(field));\n\n        hi = low + CHUNK_SIZE;\n        ptop = sqrt(hi) * 2 + 1;\n\n        for (i = 1; (p = primes.e[i]*2) < ptop; i++) {\n                for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)\n                        SET(q);\n                offset.e[i] = q + low;\n        }\n\n        for (p = 1; p < CHUNK_SIZE; p += 2)\n                if (!GET(p)) push(&primes, low + p);\n\n        low = hi;\n}\n\nint main(void)\n{\n        uint i, p, c;\n\n        while (primes.len < 20) sieve();\n        printf(\"First 20:\");\n        for (i = 0; i < 20; i++)\n                printf(\" %u\", primes.e[i]);\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 150) sieve();\n        printf(\"Between 100 and 150:\");\n        for (i = 0; i < primes.len; i++) {\n                if ((p = primes.e[i]) >= 100 && p < 150)\n                        printf(\" %u\", primes.e[i]);\n        }\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 8000) sieve();\n        for (i = c = 0; i < primes.len; i++)\n                if ((p = primes.e[i]) >= 7700 && p < 8000) c++;\n        printf(\"%u primes between 7700 and 8000\\n\", c);\n\n        for (c = 10; c <= 100000000; c *= 10) {\n                while (primes.len < c) sieve();\n                printf(\"%uth prime: %u\\n\", c, primes.e[c-1]);\n        }\n\n        return 0;\n}\n"}
{"id": 43153, "name": "Rock-paper-scissors", "Python": "from random import choice\n\nrules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}\nprevious = ['rock', 'paper', 'scissors']\n\nwhile True:\n    human = input('\\nchoose your weapon: ')\n    computer = rules[choice(previous)]  \n\n    if human in ('quit', 'exit'): break\n\n    elif human in rules:\n        previous.append(human)\n        print('the computer played', computer, end='; ')\n\n        if rules[computer] == human:  \n            print('yay you win!')\n        elif rules[human] == computer:  \n            print('the computer beat you... :(')\n        else: print(\"it's a tie!\")\n\n    else: print(\"that's not a valid choice\")\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define LEN 3 \n\n\nint rand_idx(double *p, int n)\n{\n\tdouble s = rand() / (RAND_MAX + 1.0);\n\tint i;\n\tfor (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);\n\treturn i;\n}\n\nint main()\n{\n\tint user_action, my_action;\n\tint user_rec[] = {0, 0, 0};\n\tconst char *names[] = { \"Rock\", \"Paper\", \"Scissors\" };\n\tchar str[2];\n\tconst char *winner[] = { \"We tied.\", \"Meself winned.\", \"You win.\" };\n\tdouble  p[LEN] = { 1./3, 1./3, 1./3 };\n \n\twhile (1) {\n\t\tmy_action = rand_idx(p,LEN);\n \n\t\tprintf(\"\\nYour choice [1-3]:\\n\"\n\t\t\t\"  1. Rock\\n  2. Paper\\n  3. Scissors\\n> \");\n \n\t\t\n\t\tif (!scanf(\"%d\", &user_action)) {\n\t\t\tscanf(\"%1s\", str);\n\t\t\tif (*str == 'q') {\n\t\t\t\tprintf(\"Your choices [rock : %d , paper :  %d , scissors %d] \",user_rec[0],user_rec[1], user_rec[2]); \n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tuser_action --;\n\t\tif (user_action > 2 || user_action < 0) {\n\t\t\tprintf(\"invalid choice; again\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tprintf(\"You chose %s; I chose %s. %s\\n\",\n\t\t\tnames[user_action], names[my_action],\n\t\t\twinner[(my_action - user_action + 3) % 3]);\n \n\t\tuser_rec[user_action]++;\n\t}\n}\n"}
{"id": 43154, "name": "Create a two-dimensional array at runtime", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n   int user1 = 0, user2 = 0;\n   printf(\"Enter two integers.  Space delimited, please:  \");\n   scanf(\"%d %d\",&user1, &user2);\n   int array[user1][user2];\n   array[user1/2][user2/2] = user1 + user2;\n   printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n\n   return 0;\n}\n"}
{"id": 43155, "name": "Chinese remainder theorem", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n"}
{"id": 43156, "name": "Chinese remainder theorem", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n"}
{"id": 43157, "name": "Vigenère cipher_Cryptanalysis", "Python": "from string import uppercase\nfrom operator import itemgetter\n\ndef vigenere_decrypt(target_freqs, input):\n    nchars = len(uppercase)\n    ordA = ord('A')\n    sorted_targets = sorted(target_freqs)\n\n    def frequency(input):\n        result = [[c, 0.0] for c in uppercase]\n        for c in input:\n            result[c - ordA][1] += 1\n        return result\n\n    def correlation(input):\n        result = 0.0\n        freq = frequency(input)\n        freq.sort(key=itemgetter(1))\n\n        for i, f in enumerate(freq):\n            result += f[1] * sorted_targets[i]\n        return result\n\n    cleaned = [ord(c) for c in input.upper() if c.isupper()]\n    best_len = 0\n    best_corr = -100.0\n\n    \n    \n    for i in xrange(2, len(cleaned) // 20):\n        pieces = [[] for _ in xrange(i)]\n        for j, c in enumerate(cleaned):\n            pieces[j % i].append(c)\n\n        \n        \n        corr = -0.5 * i + sum(correlation(p) for p in pieces)\n\n        if corr > best_corr:\n            best_len = i\n            best_corr = corr\n\n    if best_len == 0:\n        return (\"Text is too short to analyze\", \"\")\n\n    pieces = [[] for _ in xrange(best_len)]\n    for i, c in enumerate(cleaned):\n        pieces[i % best_len].append(c)\n\n    freqs = [frequency(p) for p in pieces]\n\n    key = \"\"\n    for fr in freqs:\n        fr.sort(key=itemgetter(1), reverse=True)\n\n        m = 0\n        max_corr = 0.0\n        for j in xrange(nchars):\n            corr = 0.0\n            c = ordA + j\n            for frc in fr:\n                d = (ord(frc[0]) - c + nchars) % nchars\n                corr += frc[1] * target_freqs[d]\n\n            if corr > max_corr:\n                m = j\n                max_corr = corr\n\n        key += chr(m + ordA)\n\n    r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)\n         for i, c in enumerate(cleaned))\n    return (key, \"\".join(r))\n\n\ndef main():\n    encoded = \n\n    english_frequences = [\n        0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n        0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n        0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n        0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\n    (key, decoded) = vigenere_decrypt(english_frequences, encoded)\n    print \"Key:\", key\n    print \"\\nText:\", decoded\n\nmain()\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *encoded =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\"\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\"\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\"\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\"\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\"\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\"\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\"\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\"\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\"\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\"\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\"\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\"\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\"\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\"\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\"\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\"\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n\nint best_match(const double *a, const double *b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n\n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n\n    return best_rotate;\n}\n\ndouble freq_every_nth(const int *msg, int len, int interval, char *key) {\n    double sum, d, ret;\n    double out[26], accu[26] = {0};\n    int i, j, rot;\n\n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n        key[j] = rot = best_match(out, freq);\n        key[j] += 'A';\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n\n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n\n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n\n    key[interval] = '\\0';\n    return ret;\n}\n\nint main() {\n    int txt[strlen(encoded)];\n    int len = 0, j;\n    char key[100];\n    double fit, best_fit = 1e100;\n\n    for (j = 0; encoded[j] != '\\0'; j++)\n        if (isupper(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n\n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        printf(\"%f, key length: %2d, %s\", fit, j, key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            printf(\" <--- best so far\");\n        }\n        printf(\"\\n\");\n    }\n\n    return 0;\n}\n"}
{"id": 43158, "name": "Pi", "Python": "def calcPi():\n    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n    while True:\n        if 4*q+r-t < n*t:\n            yield n\n            nr = 10*(r-n*t)\n            n  = ((10*(3*q+r))//t)-10*n\n            q  *= 10\n            r  = nr\n        else:\n            nr = (2*q+r)*l\n            nn = (q*(7*k)+2+(r*l))//(t*l)\n            q  *= k\n            t  *= l\n            l  += 2\n            k += 1\n            n  = nn\n            r  = nr\n\nimport sys\npi_digits = calcPi()\ni = 0\nfor d in pi_digits:\n    sys.stdout.write(str(d))\n    i += 1\n    if i == 40: print(\"\"); i = 0\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\nmpz_t tmp1, tmp2, t5, t239, pows;\nvoid actan(mpz_t res, unsigned long base, mpz_t pows)\n{\n\tint i, neg = 1;\n\tmpz_tdiv_q_ui(res, pows, base);\n\tmpz_set(tmp1, res);\n\tfor (i = 3; ; i += 2) {\n\t\tmpz_tdiv_q_ui(tmp1, tmp1, base * base);\n\t\tmpz_tdiv_q_ui(tmp2, tmp1, i);\n\t\tif (mpz_cmp_ui(tmp2, 0) == 0) break;\n\t\tif (neg) mpz_sub(res, res, tmp2);\n\t\telse\t  mpz_add(res, res, tmp2);\n\t\tneg = !neg;\n\t}\n}\n\nchar * get_digits(int n, size_t* len)\n{\n\tmpz_ui_pow_ui(pows, 10, n + 20);\n\n\tactan(t5, 5, pows);\n\tmpz_mul_ui(t5, t5, 16);\n\n\tactan(t239, 239, pows);\n\tmpz_mul_ui(t239, t239, 4);\n\n\tmpz_sub(t5, t5, t239);\n\tmpz_ui_pow_ui(pows, 10, 20);\n\tmpz_tdiv_q(t5, t5, pows);\n\n\t*len = mpz_sizeinbase(t5, 10);\n\treturn mpz_get_str(0, 0, t5);\n}\n\nint main(int c, char **v)\n{\n\tunsigned long accu = 16384, done = 0;\n\tsize_t got;\n\tchar *s;\n\n\tmpz_init(tmp1);\n\tmpz_init(tmp2);\n\tmpz_init(t5);\n\tmpz_init(t239);\n\tmpz_init(pows);\n\n\twhile (1) {\n\t\ts = get_digits(accu, &got);\n\n\t\t\n\t\tgot -= 2; \n\t\twhile (s[got] == '0' || s[got] == '9') got--;\n\n\t\tprintf(\"%.*s\", (int)(got - done), s + done);\n\t\tfree(s);\n\n\t\tdone = got;\n\n\t\t\n\t\taccu *= 2;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43159, "name": "Hofstadter Q sequence", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n"}
{"id": 43160, "name": "Hofstadter Q sequence", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n"}
{"id": 43161, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n"}
{"id": 43162, "name": "Dragon curve", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n"}
{"id": 43163, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n"}
{"id": 43164, "name": "Doubly-linked list_Element insertion", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n"}
{"id": 43165, "name": "Smarandache prime-digital sequence", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n"}
{"id": 43166, "name": "Smarandache prime-digital sequence", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n"}
{"id": 43167, "name": "Quickselect algorithm", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43168, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n"}
{"id": 43169, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n"}
{"id": 43170, "name": "State name puzzle", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n"}
{"id": 43171, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 43172, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 43173, "name": "CSV to HTML translation", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 43174, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n"}
{"id": 43175, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 43176, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 43177, "name": "LZW compression", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n"}
{"id": 43178, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 43179, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 43180, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 43181, "name": "Magic squares of odd order", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 43182, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 43183, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 43184, "name": "Yellowstone sequence", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 43185, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 43186, "name": "Cut a rectangle", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 43187, "name": "Mertens function", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n"}
{"id": 43188, "name": "Order by pair comparisons", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n"}
{"id": 43189, "name": "Order by pair comparisons", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n"}
{"id": 43190, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43191, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43192, "name": "Benford's law", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43193, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 43194, "name": "Nautical bell", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 43195, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 43196, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 43197, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 43198, "name": "Substring_Top and tail", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 43199, "name": "Legendre prime counting function", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 43200, "name": "Use another language to call a function", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n"}
{"id": 43201, "name": "Longest string challenge", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n"}
{"id": 43202, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n"}
{"id": 43203, "name": "Unprimeable numbers", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n"}
{"id": 43204, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 43205, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 43206, "name": "Pascal's triangle_Puzzle", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 43207, "name": "Chernick's Carmichael numbers", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43208, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43209, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43210, "name": "Find if a point is within a triangle", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 43211, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43212, "name": "Tau function", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43213, "name": "Sequence of primorial primes", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n"}
{"id": 43214, "name": "Sequence of primorial primes", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n"}
{"id": 43215, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 43216, "name": "Bioinformatics_base count", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 43217, "name": "Dining philosophers", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n"}
{"id": 43218, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 43219, "name": "Factorions", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 43220, "name": "Logistic curve fitting in epidemiology", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n"}
{"id": 43221, "name": "Sorting algorithms_Strand sort", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n"}
{"id": 43222, "name": "Additive primes", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n"}
{"id": 43223, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 43224, "name": "Perfect totient numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 43225, "name": "Delegates", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n"}
{"id": 43226, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 43227, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 43228, "name": "Sum of divisors", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 43229, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43230, "name": "Abbreviations, easy", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43231, "name": "Enforced immutability", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n"}
{"id": 43232, "name": "Sutherland-Hodgman polygon clipping", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n"}
{"id": 43233, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 43234, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 43235, "name": "Spiral matrix", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 43236, "name": "Spiral matrix", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 43237, "name": "Optional parameters", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n"}
{"id": 43238, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 43239, "name": "Voronoi diagram", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 43240, "name": "Call a foreign-language function", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n"}
{"id": 43241, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 43242, "name": "Knuth's algorithm S", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 43243, "name": "Faulhaber's triangle", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n"}
{"id": 43244, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43245, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43246, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43247, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n"}
{"id": 43248, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43249, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 43250, "name": "Musical scale", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 43251, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 43252, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 43253, "name": "Primes - allocate descendants to their ancestors", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n"}
{"id": 43254, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 43255, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 43256, "name": "First-class functions", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n"}
{"id": 43257, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 43258, "name": "XML_Output", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n"}
{"id": 43259, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 43260, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 43261, "name": "Plot coordinate pairs", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 43262, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n"}
{"id": 43263, "name": "Guess the number_With feedback (player)", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n"}
{"id": 43264, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n"}
{"id": 43265, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43266, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43267, "name": "Fractal tree", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n"}
{"id": 43268, "name": "Colour pinstripe_Display", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n"}
{"id": 43269, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 43270, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 43271, "name": "Doomsday rule", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 43272, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n"}
{"id": 43273, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n"}
{"id": 43274, "name": "Animate a pendulum", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 43275, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 43276, "name": "Gray code", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 43277, "name": "Create a file on magnetic tape", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n"}
{"id": 43278, "name": "Sorting algorithms_Heapsort", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 43279, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n"}
{"id": 43280, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 43281, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43282, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n"}
{"id": 43283, "name": "Euler method", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n"}
{"id": 43284, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 43285, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43286, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43287, "name": "JortSort", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n"}
{"id": 43288, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n"}
{"id": 43289, "name": "Combinations and permutations", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n"}
{"id": 43290, "name": "Sort numbers lexicographically", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n"}
{"id": 43291, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n"}
{"id": 43292, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43293, "name": "Sorting algorithms_Shell sort", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 43294, "name": "Doubly-linked list_Definition", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n"}
{"id": 43295, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 43296, "name": "Permutation test", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n"}
{"id": 43297, "name": "Möbius function", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n"}
{"id": 43298, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n"}
{"id": 43299, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 43300, "name": "Sorting algorithms_Permutation sort", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n"}
{"id": 43301, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43302, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43303, "name": "Abbreviations, simple", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 43304, "name": "Entropy", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 43305, "name": "Tokenize a string with escaping", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n"}
{"id": 43306, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n"}
{"id": 43307, "name": "Sexy primes", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef unsigned char bool;\n\nvoid sieve(bool *c, int limit) {\n    int i, p = 3, p2;\n    \n    c[0] = TRUE;\n    c[1] = TRUE;\n    \n    for (;;) {\n        p2 = p * p;\n        if (p2 >= limit) {\n            break;\n        }\n        for (i = p2; i < limit; i += 2*p) {\n            c[i] = TRUE;\n        }\n        for (;;) {\n            p += 2;\n            if (!c[p]) {\n                break;\n            }\n        }\n    }\n}\n\nvoid printHelper(const char *cat, int len, int lim, int n) {\n    const char *sp = strcmp(cat, \"unsexy primes\") ? \"sexy prime \" : \"\";\n    const char *verb = (len == 1) ? \"is\" : \"are\";\n    printf(\"Number of %s%s less than %'d = %'d\\n\", sp, cat, lim, len);\n    printf(\"The last %d %s:\\n\", n, verb);\n}\n\nvoid printArray(int *a, int len) {\n    int i;\n    printf(\"[\");\n    for (i = 0; i < len; ++i) printf(\"%d \", a[i]);\n    printf(\"\\b]\");\n}\n\nint main() {\n    int i, ix, n, lim = 1000035;\n    int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;\n    int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;\n    int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;\n    int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];\n    int last_un[10];\n    bool *sv = calloc(lim - 1, sizeof(bool)); \n    setlocale(LC_NUMERIC, \"\");\n    sieve(sv, lim);\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            unsexy++;\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pairs++;\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            trips++;\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            quads++;\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            quins++;\n        }\n    }\n    if (pairs < lpr) lpr = pairs;\n    if (trips < ltr) ltr = trips;\n    if (quads < lqd) lqd = quads;\n    if (quins < lqn) lqn = quins;\n    if (unsexy < lun) lun = unsexy;\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            un++;\n            if (un > unsexy - lun) {\n                last_un[un + lun - 1 - unsexy] = i;\n            }\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pr++;\n            if (pr > pairs - lpr) {\n                ix = pr + lpr - 1 - pairs;\n                last_pr[ix][0] = i; last_pr[ix][1] = i + 6;\n            }\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            tr++;\n            if (tr > trips - ltr) {\n                ix = tr + ltr - 1 - trips;\n                last_tr[ix][0] = i; last_tr[ix][1] = i + 6;\n                last_tr[ix][2] = i + 12;\n            }\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            qd++;\n            if (qd > quads - lqd) {\n                ix = qd + lqd - 1 - quads;\n                last_qd[ix][0] = i; last_qd[ix][1] = i + 6;\n                last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;\n            }\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            qn++;\n            if (qn > quins - lqn) {\n                ix = qn + lqn - 1 - quins;\n                last_qn[ix][0] = i; last_qn[ix][1] = i + 6;\n                last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;\n                last_qn[ix][4] = i + 24;\n            }\n        }\n    }\n\n    printHelper(\"pairs\", pairs, lim, lpr);\n    printf(\"  [\");\n    for (i = 0; i < lpr; ++i) {\n        printArray(last_pr[i], 2);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"triplets\", trips, lim, ltr);\n    printf(\"  [\");\n    for (i = 0; i < ltr; ++i) {\n        printArray(last_tr[i], 3);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quadruplets\", quads, lim, lqd);\n    printf(\"  [\");\n    for (i = 0; i < lqd; ++i) {\n        printArray(last_qd[i], 4);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quintuplets\", quins, lim, lqn);\n    printf(\"  [\");\n    for (i = 0; i < lqn; ++i) {\n        printArray(last_qn[i], 5);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"unsexy primes\", unsexy, lim, lun);\n    printf(\"  [\");\n    printArray(last_un, lun);\n    printf(\"\\b]\\n\");\n    free(sv);\n    return 0;\n}\n"}
{"id": 43308, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n"}
{"id": 43309, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n"}
{"id": 43310, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n"}
{"id": 43311, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n"}
{"id": 43312, "name": "Singly-linked list_Traversal", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n"}
{"id": 43313, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43314, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n"}
{"id": 43315, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n"}
{"id": 43316, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"}
{"id": 43317, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"}
{"id": 43318, "name": "Flipping bits game", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"}
{"id": 43319, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n"}
{"id": 43320, "name": "Hickerson series of almost integers", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n"}
{"id": 43321, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 43322, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 43323, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 43324, "name": "String interpolation (included)", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n", "C": "#include <stdio.h>\n\nint main() {\n  const char *extra = \"little\";\n  printf(\"Mary had a %s lamb.\\n\", extra);\n  return 0;\n}\n"}
{"id": 43325, "name": "Sorting algorithms_Patience sort", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint* patienceSort(int* arr,int size){\n\tint decks[size][size],i,j,min,pickedRow;\n\t\n\tint *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){\n\t\t\t\tdecks[j][count[j]] = arr[i];\n\t\t\t\tcount[j]++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmin = decks[0][count[0]-1];\n\tpickedRow = 0;\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]>0 && decks[j][count[j]-1]<min){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t}\n\t\t}\n\t\tsortedArr[i] = min;\n\t\tcount[pickedRow]--;\n\t\t\n\t\tfor(j=0;j<size;j++)\n\t\t\tif(count[j]>0){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\t\n\tfree(count);\n\tfree(decks);\n\t\n\treturn sortedArr;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr, *sortedArr, i;\n\t\n\tif(argC==0)\n\t\tprintf(\"Usage : %s <integers to be sorted separated by space>\");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i<=argC;i++)\n\t\t\tarr[i-1] = atoi(argV[i]);\n\t\t\n\t\tsortedArr = patienceSort(arr,argC-1);\n\t\t\n\t\tfor(i=0;i<argC-1;i++)\n\t\t\tprintf(\"%d \",sortedArr[i]);\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 43326, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 43327, "name": "Bioinformatics_Sequence mutation", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 43328, "name": "Tau number", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    unsigned int p;\n\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int count = 0;\n    unsigned int n;\n\n    printf(\"The first %d tau numbers are:\\n\", limit);\n    for (n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            printf(\"%6d\", n);\n            ++count;\n            if (count % 10 == 0) {\n                printf(\"\\n\");\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43329, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n"}
{"id": 43330, "name": "Determinant and permanent", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n"}
{"id": 43331, "name": "Partition function P", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n", "C": "#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <gmp.h>\n\nmpz_t* partition(uint64_t n) {\n\tmpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));\n\tmpz_init_set_ui(pn[0], 1);\n\tmpz_init_set_ui(pn[1], 1);\n\tfor (uint64_t i = 2; i < n + 2; i ++) {\n\t\tmpz_init(pn[i]);\n\t\tfor (uint64_t k = 1, penta; ; k++) {\n\t\t\tpenta = k * (3 * k - 1) >> 1;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t\tpenta += k;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t}\n\t}\n\tmpz_t *tmp = &pn[n + 1];\n\tfor (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);\n\tfree(pn);\n\treturn tmp;\n}\n\nint main(int argc, char const *argv[]) {\n\tclock_t start = clock();\n\tmpz_t *p = partition(6666);\n\tgmp_printf(\"%Zd\\n\", p);\n\tprintf(\"Elapsed time: %.04f seconds\\n\",\n\t\t(double)(clock() - start) / (double)CLOCKS_PER_SEC);\n\treturn 0;\n}\n"}
{"id": 43332, "name": "Bitwise operations", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n"}
{"id": 43333, "name": "Dragon curve", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n"}
{"id": 43334, "name": "Read a file line by line", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n"}
{"id": 43335, "name": "Doubly-linked list_Element insertion", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n"}
{"id": 43336, "name": "Quickselect algorithm", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 43337, "name": "Non-decimal radices_Convert", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n"}
{"id": 43338, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n"}
{"id": 43339, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n"}
{"id": 43340, "name": "Classes", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n"}
{"id": 43341, "name": "Kaprekar numbers", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 43342, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43343, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 43344, "name": "Hofstadter Figure-Figure sequences", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 43345, "name": "Anonymous recursion", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n"}
{"id": 43346, "name": "Universal Turing machine", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 43347, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 43348, "name": "Universal Turing machine", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 43349, "name": "Create a file", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 43350, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n"}
{"id": 43351, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n"}
{"id": 43352, "name": "Enforced immutability", "C#": "readonly DateTime now = DateTime.Now;\n", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n"}
{"id": 43353, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43354, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43355, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43356, "name": "Spiral matrix", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n"}
{"id": 43357, "name": "Faulhaber's triangle", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n"}
{"id": 43358, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 43359, "name": "Command-line arguments", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 43360, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"}
{"id": 43361, "name": "User input_Text", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 43362, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 43363, "name": "Cartesian product of two or more lists", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 43364, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 43365, "name": "First-class functions", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n"}
{"id": 43366, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n"}
{"id": 43367, "name": "XML_Output", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 43368, "name": "Regular expressions", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n"}
{"id": 43369, "name": "Guess the number_With feedback (player)", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n"}
{"id": 43370, "name": "Hash from two arrays", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n"}
{"id": 43371, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 43372, "name": "Bin given limits", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 43373, "name": "Animate a pendulum", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n"}
{"id": 43374, "name": "Sorting algorithms_Heapsort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 43375, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 43376, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 43377, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 43378, "name": "Sierpinski carpet", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n"}
{"id": 43379, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 43380, "name": "Merge and aggregate datasets", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n"}
{"id": 43381, "name": "Euler method", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n"}
{"id": 43382, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 43383, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 43384, "name": "JortSort", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n"}
{"id": 43385, "name": "Leap year", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n"}
{"id": 43386, "name": "Sort numbers lexicographically", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n"}
{"id": 43387, "name": "Number names", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n"}
{"id": 43388, "name": "Compare length of two strings", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43389, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n"}
{"id": 43390, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n"}
{"id": 43391, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 43392, "name": "Averages_Arithmetic mean", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n"}
{"id": 43393, "name": "Entropy", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n"}
{"id": 43394, "name": "Tokenize a string with escaping", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n"}
{"id": 43395, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n"}
{"id": 43396, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 43397, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n"}
{"id": 43398, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n"}
{"id": 43399, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n"}
{"id": 43400, "name": "Singly-linked list_Traversal", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n"}
{"id": 43401, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43402, "name": "Delete a file", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n"}
{"id": 43403, "name": "Discordian date", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 43404, "name": "Average loop length", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 43405, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 43406, "name": "String interpolation (included)", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n"}
{"id": 43407, "name": "String interpolation (included)", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n"}
{"id": 43408, "name": "Partition function P", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n"}
{"id": 43409, "name": "Partition function P", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n"}
{"id": 43410, "name": "Numbers with prime digits whose sum is 13", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n"}
{"id": 43411, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n"}
{"id": 43412, "name": "Dragon curve", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n"}
{"id": 43413, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n"}
{"id": 43414, "name": "Doubly-linked list_Element insertion", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n"}
{"id": 43415, "name": "Doubly-linked list_Element insertion", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n"}
{"id": 43416, "name": "Smarandache prime-digital sequence", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n"}
{"id": 43417, "name": "Quickselect algorithm", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 43418, "name": "Non-decimal radices_Convert", "Python": "i = int('1a',16)  \n", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n"}
{"id": 43419, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n"}
{"id": 43420, "name": "Main step of GOST 28147-89", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n", "C++": "UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)\n{\n    UINT_64 N;\n\tN = N1;\n\tN = (N<<32)|N2;\n\treturn UINT_64(N);\n}\n\nUINT_32 TGost::ReplaceBlock(UINT_32 x)\n{   \n    register i;\n    UINT_32 res = 0UL;\n    for(i=7;i>=0;i--)\n    {\n       ui4_0 = x>>(i*4);\n       ui4_0 = BS[ui4_0][i];\n       res = (res<<4)|ui4_0;\n    }\n    return res;\n}\n\nUINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)\n{\n   UINT_32 N1,N2,S=0UL;\n   N1=UINT_32(N);\n   N2=N>>32;\n   S = N1 + X % 0x4000000000000;\n   S = ReplaceBlock(S);\n   S = (S<<11)|(S>>21);\n   S ^= N2;\n   N2 = N1;\n   N1 = S;\n   return SWAP32(N2,N1);\n}\n"}
{"id": 43421, "name": "State name puzzle", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n"}
{"id": 43422, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n"}
{"id": 43423, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 43424, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 43425, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n"}
{"id": 43426, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43427, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43428, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n"}
{"id": 43429, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 43430, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 43431, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 43432, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 43433, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43434, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43435, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 43436, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 43437, "name": "Mertens function", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n"}
{"id": 43438, "name": "Mertens function", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n"}
{"id": 43439, "name": "Order by pair comparisons", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n"}
{"id": 43440, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 43441, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 43442, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 43443, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 43444, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n"}
{"id": 43445, "name": "Snake", "Python": "from __future__ import annotations\n\nimport itertools\nimport random\n\nfrom enum import Enum\n\nfrom typing import Any\nfrom typing import Tuple\n\nimport pygame as pg\n\nfrom pygame import Color\nfrom pygame import Rect\n\nfrom pygame.surface import Surface\n\nfrom pygame.sprite import AbstractGroup\nfrom pygame.sprite import Group\nfrom pygame.sprite import RenderUpdates\nfrom pygame.sprite import Sprite\n\n\nclass Direction(Enum):\n    UP = (0, -1)\n    DOWN = (0, 1)\n    LEFT = (-1, 0)\n    RIGHT = (1, 0)\n\n    def opposite(self, other: Direction):\n        return (self[0] + other[0], self[1] + other[1]) == (0, 0)\n\n    def __getitem__(self, i: int):\n        return self.value[i]\n\n\nclass SnakeHead(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        facing: Direction,\n        bounds: Rect,\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"aquamarine4\"))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n        self.facing = facing\n        self.size = size\n        self.speed = size\n        self.bounds = bounds\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        \n        self.rect.move_ip(\n            (\n                self.facing[0] * self.speed,\n                self.facing[1] * self.speed,\n            )\n        )\n\n        \n        if self.rect.right > self.bounds.right:\n            self.rect.left = 0\n        elif self.rect.left < 0:\n            self.rect.right = self.bounds.right\n\n        if self.rect.bottom > self.bounds.bottom:\n            self.rect.top = 0\n        elif self.rect.top < 0:\n            self.rect.bottom = self.bounds.bottom\n\n    def change_direction(self, direction: Direction):\n        if not self.facing == direction and not direction.opposite(self.facing):\n            self.facing = direction\n\n\nclass SnakeBody(Sprite):\n    def __init__(\n        self,\n        size: int,\n        position: Tuple[int, int],\n        colour: str = \"white\",\n    ) -> None:\n        super().__init__()\n        self.image = Surface((size, size))\n        self.image.fill(Color(colour))\n        self.rect = self.image.get_rect()\n        self.rect.center = position\n\n\nclass Snake(RenderUpdates):\n    def __init__(self, game: Game) -> None:\n        self.segment_size = game.segment_size\n        self.colours = itertools.cycle([\"aquamarine1\", \"aquamarine3\"])\n\n        self.head = SnakeHead(\n            size=self.segment_size,\n            position=game.rect.center,\n            facing=Direction.RIGHT,\n            bounds=game.rect,\n        )\n\n        neck = [\n            SnakeBody(\n                size=self.segment_size,\n                position=game.rect.center,\n                colour=next(self.colours),\n            )\n            for _ in range(2)\n        ]\n\n        super().__init__(*[self.head, *neck])\n\n        self.body = Group()\n        self.tail = neck[-1]\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        self.head.update()\n\n        \n        segments = self.sprites()\n        for i in range(len(segments) - 1, 0, -1):\n            \n            segments[i].rect.center = segments[i - 1].rect.center\n\n    def change_direction(self, direction: Direction):\n        self.head.change_direction(direction)\n\n    def grow(self):\n        tail = SnakeBody(\n            size=self.segment_size,\n            position=self.tail.rect.center,\n            colour=next(self.colours),\n        )\n        self.tail = tail\n        self.add(self.tail)\n        self.body.add(self.tail)\n\n\nclass SnakeFood(Sprite):\n    def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None:\n        super().__init__(*groups)\n        self.image = Surface((size, size))\n        self.image.fill(Color(\"red\"))\n        self.rect = self.image.get_rect()\n\n        self.rect.topleft = (\n            random.randint(0, game.rect.width),\n            random.randint(0, game.rect.height),\n        )\n\n        self.rect.clamp_ip(game.rect)\n\n        \n        \n        while pg.sprite.spritecollideany(self, game.snake):\n            self.rect.topleft = (\n                random.randint(0, game.rect.width),\n                random.randint(0, game.rect.height),\n            )\n\n            self.rect.clamp_ip(game.rect)\n\n\nclass Game:\n    def __init__(self) -> None:\n        self.rect = Rect(0, 0, 640, 480)\n        self.background = Surface(self.rect.size)\n        self.background.fill(Color(\"black\"))\n\n        self.score = 0\n        self.framerate = 16\n\n        self.segment_size = 10\n        self.snake = Snake(self)\n        self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size))\n\n        pg.init()\n\n    def _init_display(self) -> Surface:\n        bestdepth = pg.display.mode_ok(self.rect.size, 0, 32)\n        screen = pg.display.set_mode(self.rect.size, 0, bestdepth)\n\n        pg.display.set_caption(\"Snake\")\n        pg.mouse.set_visible(False)\n\n        screen.blit(self.background, (0, 0))\n        pg.display.flip()\n\n        return screen\n\n    def draw(self, screen: Surface):\n        dirty = self.snake.draw(screen)\n        pg.display.update(dirty)\n\n        dirty = self.food_group.draw(screen)\n        pg.display.update(dirty)\n\n    def update(self, screen):\n        self.food_group.clear(screen, self.background)\n        self.food_group.update()\n        self.snake.clear(screen, self.background)\n        self.snake.update()\n\n    def main(self) -> int:\n        screen = self._init_display()\n        clock = pg.time.Clock()\n\n        while self.snake.head.alive():\n            for event in pg.event.get():\n                if event.type == pg.QUIT or (\n                    event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q)\n                ):\n                    return self.score\n\n            \n            keystate = pg.key.get_pressed()\n\n            if keystate[pg.K_RIGHT]:\n                self.snake.change_direction(Direction.RIGHT)\n            elif keystate[pg.K_LEFT]:\n                self.snake.change_direction(Direction.LEFT)\n            elif keystate[pg.K_UP]:\n                self.snake.change_direction(Direction.UP)\n            elif keystate[pg.K_DOWN]:\n                self.snake.change_direction(Direction.DOWN)\n\n            \n            self.update(screen)\n\n            \n            for food in pg.sprite.spritecollide(\n                self.snake.head, self.food_group, dokill=False\n            ):\n                food.kill()\n                self.snake.grow()\n                self.score += 1\n\n                \n                if self.score % 5 == 0:\n                    self.framerate += 1\n\n                self.food_group.add(SnakeFood(self, self.segment_size))\n\n            \n            if pg.sprite.spritecollideany(self.snake.head, self.snake.body):\n                self.snake.head.kill()\n\n            self.draw(screen)\n            clock.tick(self.framerate)\n\n        return self.score\n\n\nif __name__ == \"__main__\":\n    game = Game()\n    score = game.main()\n    print(score)\n", "C++": "#include <windows.h>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nconst int WID = 60, HEI = 30, MAX_LEN = 600;\nenum DIR { NORTH, EAST, SOUTH, WEST };\n\nclass snake {\npublic:\n    snake() {\n        console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( \"Snake\" ); \n        COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );\n        SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );\n        CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );\n    }\n    void play() {\n        std::string a;\n        while( 1 ) {\n            createField(); alive = true;\n            while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }\n            COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );\n            SetConsoleTextAttribute( console, 0x000b );\n            std::cout << \"Play again [Y/N]? \"; std::cin >> a;\n            if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;\n        }\n    }\nprivate:\n    void createField() {\n        COORD coord = { 0, 0 }; DWORD c;\n        FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );\n        FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );\n        SetConsoleCursorPosition( console, coord );\n        int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;\n        for( x = 0; x < WID; x++ ) {\n            brd[x] = brd[x + WID * ( HEI - 1 )] = '+';\n        }\n        for( ; y < HEI; y++ ) {\n            brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';\n        }\n        do {\n            x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n        } while( brd[x + WID * y] );\n        brd[x + WID * y] = '@';\n        tailIdx = 0; headIdx = 4; x = 3; y = 2;\n        for( int c = tailIdx; c < headIdx; c++ ) {\n            brd[x + WID * y] = '#';\n            snk[c].X = 3 + c; snk[c].Y = 2;\n        }\n        head = snk[3]; dir = EAST; points = 0;\n    }\n    void readKey() {\n        if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;\n        if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;\n        if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;\n        if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;\n    }\n    void drawField() {\n        COORD coord; char t;\n        for( int y = 0; y < HEI; y++ ) {\n            coord.Y = y;\n            for( int x = 0; x < WID; x++ ) {\n                t = brd[x + WID * y]; if( !t ) continue;\n                coord.X = x; SetConsoleCursorPosition( console, coord );\n                if( coord.X == head.X && coord.Y == head.Y ) {\n                    SetConsoleTextAttribute( console, 0x002e );\n                    std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );\n                    continue;\n                }\n                switch( t ) {\n                    case '#': SetConsoleTextAttribute( console, 0x002a ); break;\n                    case '+': SetConsoleTextAttribute( console, 0x0019 ); break;\n                    case '@': SetConsoleTextAttribute( console, 0x004c ); break;\n                }\n                std::cout << t; SetConsoleTextAttribute( console, 0x0000 );\n            }\n        }\n        std::cout << t; SetConsoleTextAttribute( console, 0x0007 );\n        COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );\n        std::cout << \"Points: \" << points;\n    }\n    void moveSnake() {\n        switch( dir ) {\n            case NORTH: head.Y--; break;\n            case EAST: head.X++; break;\n            case SOUTH: head.Y++; break;\n            case WEST: head.X--; break;\n        }\n        char t = brd[head.X + WID * head.Y];\n        if( t && t != '@' ) { alive = false; return; }\n        brd[head.X + WID * head.Y] = '#';\n        snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;\n        if( ++headIdx >= MAX_LEN ) headIdx = 0;\n        if( t == '@' ) {\n            points++; int x, y;\n            do {\n                x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n            } while( brd[x + WID * y] );\n            brd[x + WID * y] = '@'; return;\n        }\n        SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';\n        brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;\n        if( ++tailIdx >= MAX_LEN ) tailIdx = 0;\n    }\n    bool alive; char brd[WID * HEI]; \n    HANDLE console; DIR dir; COORD snk[MAX_LEN];\n    COORD head; int tailIdx, headIdx, points;\n};\nint main( int argc, char* argv[] ) {\n    srand( static_cast<unsigned>( time( NULL ) ) );\n    snake s; s.play(); return 0;\n}\n"}
{"id": 43446, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43447, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43448, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43449, "name": "Legendre prime counting function", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n"}
{"id": 43450, "name": "Legendre prime counting function", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n"}
{"id": 43451, "name": "Use another language to call a function", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n"}
{"id": 43452, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n"}
{"id": 43453, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 43454, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 43455, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 43456, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 43457, "name": "Unprimeable numbers", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n"}
{"id": 43458, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 43459, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 43460, "name": "Chernick's Carmichael numbers", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43461, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 43462, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 43463, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43464, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43465, "name": "Sequence of primorial primes", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43466, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 43467, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 43468, "name": "Dining philosophers", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n"}
{"id": 43469, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 43470, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 43471, "name": "Logistic curve fitting in epidemiology", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n"}
{"id": 43472, "name": "Sorting algorithms_Strand sort", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n"}
{"id": 43473, "name": "Additive primes", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n"}
{"id": 43474, "name": "Inverted syntax", "Python": "x = truevalue if condition else falsevalue\n", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n"}
{"id": 43475, "name": "Inverted syntax", "Python": "x = truevalue if condition else falsevalue\n", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n"}
{"id": 43476, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43477, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43478, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43479, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n"}
{"id": 43480, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43481, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43482, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43483, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43484, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43485, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n"}
{"id": 43486, "name": "Sutherland-Hodgman polygon clipping", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43487, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43488, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43489, "name": "Spiral matrix", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n"}
{"id": 43490, "name": "Optional parameters", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n"}
{"id": 43491, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 43492, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 43493, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n"}
{"id": 43494, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 43495, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 43496, "name": "Faulhaber's triangle", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n"}
{"id": 43497, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 43498, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 43499, "name": "Word wheel", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43500, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"}
{"id": 43501, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 43502, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 43503, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 43504, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 43505, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 43506, "name": "Primes - allocate descendants to their ancestors", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n"}
{"id": 43507, "name": "Primes - allocate descendants to their ancestors", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n"}
{"id": 43508, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 43509, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 43510, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n"}
{"id": 43511, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n"}
{"id": 43512, "name": "XML_Output", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 43513, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 43514, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 43515, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 43516, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n"}
{"id": 43517, "name": "Guess the number_With feedback (player)", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n"}
{"id": 43518, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n"}
{"id": 43519, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 43520, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 43521, "name": "Fractal tree", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n"}
{"id": 43522, "name": "Colour pinstripe_Display", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n"}
{"id": 43523, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 43524, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 43525, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n"}
{"id": 43526, "name": "Animate a pendulum", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n"}
{"id": 43527, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 43528, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 43529, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 43530, "name": "Create a file on magnetic tape", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n"}
{"id": 43531, "name": "Sorting algorithms_Heapsort", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 43532, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 43533, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 43534, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 43535, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n"}
{"id": 43536, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 43537, "name": "Merge and aggregate datasets", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n"}
{"id": 43538, "name": "Euler method", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n"}
{"id": 43539, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 43540, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 43541, "name": "JortSort", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n"}
{"id": 43542, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n"}
{"id": 43543, "name": "Combinations and permutations", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n"}
{"id": 43544, "name": "Sort numbers lexicographically", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n"}
{"id": 43545, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n"}
{"id": 43546, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43547, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n"}
{"id": 43548, "name": "Doubly-linked list_Definition", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n"}
{"id": 43549, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n"}
{"id": 43550, "name": "Permutation test", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n"}
{"id": 43551, "name": "Möbius function", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43552, "name": "Increment a numerical string", "Python": "next = str(int('123') + 1)\n", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n"}
{"id": 43553, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 43554, "name": "Sorting algorithms_Permutation sort", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n"}
{"id": 43555, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n"}
{"id": 43556, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43557, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43558, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n"}
{"id": 43559, "name": "Tokenize a string with escaping", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n"}
{"id": 43560, "name": "Hello world_Text", "Python": "print \"Hello world!\"\n", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n"}
{"id": 43561, "name": "Sexy primes", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n"}
{"id": 43562, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 43563, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n"}
{"id": 43564, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n"}
{"id": 43565, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n"}
{"id": 43566, "name": "Singly-linked list_Traversal", "Python": "for node in lst:\n    print node.value\n", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n"}
{"id": 43567, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43568, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n"}
{"id": 43569, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 43570, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"}
{"id": 43571, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"}
{"id": 43572, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"}
{"id": 43573, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n"}
{"id": 43574, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n"}
{"id": 43575, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 43576, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 43577, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n"}
{"id": 43578, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n"}
{"id": 43579, "name": "Sorting algorithms_Patience sort", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n", "C++": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <iterator>\n#include <algorithm>\n#include <cassert>\n\ntemplate <class E>\nstruct pile_less {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() < pile2.top();\n  }\n};\n\ntemplate <class E>\nstruct pile_greater {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() > pile2.top();\n  }\n};\n\n\ntemplate <class Iterator>\nvoid patience_sort(Iterator first, Iterator last) {\n  typedef typename std::iterator_traits<Iterator>::value_type E;\n  typedef std::stack<E> Pile;\n\n  std::vector<Pile> piles;\n  \n  for (Iterator it = first; it != last; it++) {\n    E& x = *it;\n    Pile newPile;\n    newPile.push(x);\n    typename std::vector<Pile>::iterator i =\n      std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());\n    if (i != piles.end())\n      i->push(x);\n    else\n      piles.push_back(newPile);\n  }\n\n  \n  \n  std::make_heap(piles.begin(), piles.end(), pile_greater<E>());\n  for (Iterator it = first; it != last; it++) {\n    std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());\n    Pile &smallPile = piles.back();\n    *it = smallPile.top();\n    smallPile.pop();\n    if (smallPile.empty())\n      piles.pop_back();\n    else\n      std::push_heap(piles.begin(), piles.end(), pile_greater<E>());\n  }\n  assert(piles.empty());\n}\n\nint main() {\n  int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n  patience_sort(a, a+sizeof(a)/sizeof(*a));\n  std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  return 0;\n}\n"}
{"id": 43580, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n"}
{"id": 43581, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n"}
{"id": 43582, "name": "Tau number", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"The first \" << limit << \" tau numbers are:\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            std::cout << std::setw(6) << n;\n            ++count;\n            if (count % 10 == 0)\n                std::cout << '\\n';\n        }\n    }\n}\n"}
{"id": 43583, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n"}
{"id": 43584, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n"}
{"id": 43585, "name": "Partition function P", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n"}
{"id": 43586, "name": "Wireworld", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n", "C++": "#include <ggi/ggi.h>\n#include <set>\n#include <map>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <unistd.h> \n\nenum cell_type { none, wire, head, tail };\n\n\n\n\n\n\n\nclass display\n{\npublic:\n  display(int sizex, int sizey, int pixsizex, int pixsizey,\n          ggi_color* colors);\n  ~display()\n  {\n    ggiClose(visual);\n    ggiExit();\n  }\n\n  void flush();\n  bool keypressed() { return ggiKbhit(visual); }\n  void clear();\n  void putpixel(int x, int y, cell_type c);\nprivate:\n  ggi_visual_t visual;\n  int size_x, size_y;\n  int pixel_size_x, pixel_size_y;\n  ggi_pixel pixels[4];\n};\n\ndisplay::display(int sizex, int sizey, int pixsizex, int pixsizey,\n                 ggi_color* colors):\n  pixel_size_x(pixsizex),\n  pixel_size_y(pixsizey)\n{\n  if (ggiInit() < 0)\n  {\n    std::cerr << \"couldn't open ggi\\n\";\n    exit(1);\n  }\n\n  visual = ggiOpen(NULL);\n  if (!visual)\n  {\n    ggiPanic(\"couldn't open visual\\n\");\n  }\n\n  ggi_mode mode;\n  if (ggiCheckGraphMode(visual, sizex, sizey,\n                        GGI_AUTO, GGI_AUTO, GT_4BIT,\n                        &mode) != 0)\n  {\n    if (GT_DEPTH(mode.graphtype) < 2) \n      ggiPanic(\"low-color displays are not supported!\\n\");\n  }\n  if (ggiSetMode(visual, &mode) != 0)\n  {\n    ggiPanic(\"couldn't set graph mode\\n\");\n  }\n  ggiAddFlags(visual, GGIFLAG_ASYNC);\n\n  size_x = mode.virt.x;\n  size_y = mode.virt.y;\n\n  for (int i = 0; i < 4; ++i)\n    pixels[i] = ggiMapColor(visual, colors+i);\n}\n\nvoid display::flush()\n{\n  \n  ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));\n\n  \n  ggiFlush(visual);\n\n  \n  \n  \n  ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));\n}\n\nvoid display::clear()\n{\n  ggiSetGCForeground(visual, pixels[0]);\n  ggiDrawBox(visual, 0, 0, size_x, size_y);\n}\n\nvoid display::putpixel(int x, int y, cell_type cell)\n{\n  \n  \n  ggiSetGCForeground(visual, pixels[cell]);\n  ggiDrawBox(visual,\n             x*pixel_size_x, y*pixel_size_y,\n             pixel_size_x, pixel_size_y);\n}\n\n\n\n\n\n\nclass wireworld\n{\npublic:\n  void set(int posx, int posy, cell_type type);\n  void draw(display& destination);\n  void step();\nprivate:\n  typedef std::pair<int, int> position;\n  typedef std::set<position> position_set;\n  typedef position_set::iterator positer;\n  position_set wires, heads, tails;\n};\n\nvoid wireworld::set(int posx, int posy, cell_type type)\n{\n  position p(posx, posy);\n  wires.erase(p);\n  heads.erase(p);\n  tails.erase(p);\n  switch(type)\n  {\n  case head:\n    heads.insert(p);\n    break;\n  case tail:\n    tails.insert(p);\n    break;\n  case wire:\n    wires.insert(p);\n    break;\n  }\n}\n\nvoid wireworld::draw(display& destination)\n{\n  destination.clear();\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    destination.putpixel(i->first, i->second, head);\n  for (positer i = tails.begin(); i != tails.end(); ++i)\n    destination.putpixel(i->first, i->second, tail);\n  for (positer i = wires.begin(); i != wires.end(); ++i)\n    destination.putpixel(i->first, i->second, wire);\n  destination.flush();\n}\n\nvoid wireworld::step()\n{\n  std::map<position, int> new_heads;\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    for (int dx = -1; dx <= 1; ++dx)\n      for (int dy = -1; dy <= 1; ++dy)\n      {\n        position pos(i->first + dx, i->second + dy);\n        if (wires.count(pos))\n          new_heads[pos]++;\n      }\n  wires.insert(tails.begin(), tails.end());\n  tails.swap(heads);\n  heads.clear();\n  for (std::map<position, int>::iterator i = new_heads.begin();\n       i != new_heads.end();\n       ++i)\n  {\n\n    if (i->second < 3)\n    {\n      wires.erase(i->first);\n      heads.insert(i->first);\n    }\n  }\n}\n\nggi_color colors[4] =\n  {{ 0x0000, 0x0000, 0x0000 },  \n   { 0x8000, 0x8000, 0x8000 },  \n   { 0xffff, 0xffff, 0x0000 },  \n   { 0xffff, 0x0000, 0x0000 }}; \n\nint main(int argc, char* argv[])\n{\n  int display_x = 800;\n  int display_y = 600;\n  int pixel_x = 5;\n  int pixel_y = 5;\n\n  if (argc < 2)\n  {\n    std::cerr << \"No file name given!\\n\";\n    return 1;\n  }\n\n  \n  std::ifstream f(argv[1]);\n  wireworld w;\n  std::string line;\n  int line_number = 0;\n  while (std::getline(f, line))\n  {\n    for (int col = 0; col < line.size(); ++col)\n    {\n      switch (line[col])\n      {\n      case 'h': case 'H':\n        w.set(col, line_number, head);\n        break;\n      case 't': case 'T':\n        w.set(col, line_number, tail);\n        break;\n      case 'w': case 'W': case '.':\n        w.set(col, line_number, wire);\n        break;\n      default:\n        std::cerr << \"unrecognized character: \" << line[col] << \"\\n\";\n        return 1;\n      case ' ':\n        ; \n      }\n    }\n    ++line_number;\n  }\n\n  display d(display_x, display_y, pixel_x, pixel_y, colors);\n\n  w.draw(d);\n\n  while (!d.keypressed())\n  {\n    usleep(100000);\n    w.step();\n    w.draw(d);\n  }\n  std::cout << std::endl;\n}\n"}
{"id": 43587, "name": "Wireworld", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n", "C++": "#include <ggi/ggi.h>\n#include <set>\n#include <map>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <unistd.h> \n\nenum cell_type { none, wire, head, tail };\n\n\n\n\n\n\n\nclass display\n{\npublic:\n  display(int sizex, int sizey, int pixsizex, int pixsizey,\n          ggi_color* colors);\n  ~display()\n  {\n    ggiClose(visual);\n    ggiExit();\n  }\n\n  void flush();\n  bool keypressed() { return ggiKbhit(visual); }\n  void clear();\n  void putpixel(int x, int y, cell_type c);\nprivate:\n  ggi_visual_t visual;\n  int size_x, size_y;\n  int pixel_size_x, pixel_size_y;\n  ggi_pixel pixels[4];\n};\n\ndisplay::display(int sizex, int sizey, int pixsizex, int pixsizey,\n                 ggi_color* colors):\n  pixel_size_x(pixsizex),\n  pixel_size_y(pixsizey)\n{\n  if (ggiInit() < 0)\n  {\n    std::cerr << \"couldn't open ggi\\n\";\n    exit(1);\n  }\n\n  visual = ggiOpen(NULL);\n  if (!visual)\n  {\n    ggiPanic(\"couldn't open visual\\n\");\n  }\n\n  ggi_mode mode;\n  if (ggiCheckGraphMode(visual, sizex, sizey,\n                        GGI_AUTO, GGI_AUTO, GT_4BIT,\n                        &mode) != 0)\n  {\n    if (GT_DEPTH(mode.graphtype) < 2) \n      ggiPanic(\"low-color displays are not supported!\\n\");\n  }\n  if (ggiSetMode(visual, &mode) != 0)\n  {\n    ggiPanic(\"couldn't set graph mode\\n\");\n  }\n  ggiAddFlags(visual, GGIFLAG_ASYNC);\n\n  size_x = mode.virt.x;\n  size_y = mode.virt.y;\n\n  for (int i = 0; i < 4; ++i)\n    pixels[i] = ggiMapColor(visual, colors+i);\n}\n\nvoid display::flush()\n{\n  \n  ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));\n\n  \n  ggiFlush(visual);\n\n  \n  \n  \n  ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));\n}\n\nvoid display::clear()\n{\n  ggiSetGCForeground(visual, pixels[0]);\n  ggiDrawBox(visual, 0, 0, size_x, size_y);\n}\n\nvoid display::putpixel(int x, int y, cell_type cell)\n{\n  \n  \n  ggiSetGCForeground(visual, pixels[cell]);\n  ggiDrawBox(visual,\n             x*pixel_size_x, y*pixel_size_y,\n             pixel_size_x, pixel_size_y);\n}\n\n\n\n\n\n\nclass wireworld\n{\npublic:\n  void set(int posx, int posy, cell_type type);\n  void draw(display& destination);\n  void step();\nprivate:\n  typedef std::pair<int, int> position;\n  typedef std::set<position> position_set;\n  typedef position_set::iterator positer;\n  position_set wires, heads, tails;\n};\n\nvoid wireworld::set(int posx, int posy, cell_type type)\n{\n  position p(posx, posy);\n  wires.erase(p);\n  heads.erase(p);\n  tails.erase(p);\n  switch(type)\n  {\n  case head:\n    heads.insert(p);\n    break;\n  case tail:\n    tails.insert(p);\n    break;\n  case wire:\n    wires.insert(p);\n    break;\n  }\n}\n\nvoid wireworld::draw(display& destination)\n{\n  destination.clear();\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    destination.putpixel(i->first, i->second, head);\n  for (positer i = tails.begin(); i != tails.end(); ++i)\n    destination.putpixel(i->first, i->second, tail);\n  for (positer i = wires.begin(); i != wires.end(); ++i)\n    destination.putpixel(i->first, i->second, wire);\n  destination.flush();\n}\n\nvoid wireworld::step()\n{\n  std::map<position, int> new_heads;\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    for (int dx = -1; dx <= 1; ++dx)\n      for (int dy = -1; dy <= 1; ++dy)\n      {\n        position pos(i->first + dx, i->second + dy);\n        if (wires.count(pos))\n          new_heads[pos]++;\n      }\n  wires.insert(tails.begin(), tails.end());\n  tails.swap(heads);\n  heads.clear();\n  for (std::map<position, int>::iterator i = new_heads.begin();\n       i != new_heads.end();\n       ++i)\n  {\n\n    if (i->second < 3)\n    {\n      wires.erase(i->first);\n      heads.insert(i->first);\n    }\n  }\n}\n\nggi_color colors[4] =\n  {{ 0x0000, 0x0000, 0x0000 },  \n   { 0x8000, 0x8000, 0x8000 },  \n   { 0xffff, 0xffff, 0x0000 },  \n   { 0xffff, 0x0000, 0x0000 }}; \n\nint main(int argc, char* argv[])\n{\n  int display_x = 800;\n  int display_y = 600;\n  int pixel_x = 5;\n  int pixel_y = 5;\n\n  if (argc < 2)\n  {\n    std::cerr << \"No file name given!\\n\";\n    return 1;\n  }\n\n  \n  std::ifstream f(argv[1]);\n  wireworld w;\n  std::string line;\n  int line_number = 0;\n  while (std::getline(f, line))\n  {\n    for (int col = 0; col < line.size(); ++col)\n    {\n      switch (line[col])\n      {\n      case 'h': case 'H':\n        w.set(col, line_number, head);\n        break;\n      case 't': case 'T':\n        w.set(col, line_number, tail);\n        break;\n      case 'w': case 'W': case '.':\n        w.set(col, line_number, wire);\n        break;\n      default:\n        std::cerr << \"unrecognized character: \" << line[col] << \"\\n\";\n        return 1;\n      case ' ':\n        ; \n      }\n    }\n    ++line_number;\n  }\n\n  display d(display_x, display_y, pixel_x, pixel_y, colors);\n\n  w.draw(d);\n\n  while (!d.keypressed())\n  {\n    usleep(100000);\n    w.step();\n    w.draw(d);\n  }\n  std::cout << std::endl;\n}\n"}
{"id": 43588, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nconst double epsilon = numeric_limits<float>().epsilon();\nconst numeric_limits<double> DOUBLE;\nconst double MIN = DOUBLE.min();\nconst double MAX = DOUBLE.max();\n\nstruct Point { const double x, y; };\n\nstruct Edge {\n    const Point a, b;\n\n    bool operator()(const Point& p) const\n    {\n        if (a.y > b.y) return Edge{ b, a }(p);\n        if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });\n        if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;\n        if (p.x < min(a.x, b.x)) return true;\n        auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;\n        auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;\n        return blue >= red;\n    }\n};\n\nstruct Figure {\n    const string  name;\n    const initializer_list<Edge> edges;\n\n    bool contains(const Point& p) const\n    {\n        auto c = 0;\n        for (auto e : edges) if (e(p)) c++;\n        return c % 2 != 0;\n    }\n\n    template<unsigned char W = 3>\n    void check(const initializer_list<Point>& points, ostream& os) const\n    {\n        os << \"Is point inside figure \" << name <<  '?' << endl;\n        for (auto p : points)\n            os << \"  (\" << setw(W) << p.x << ',' << setw(W) << p.y << \"): \" << boolalpha << contains(p) << endl;\n        os << endl;\n    }\n};\n\nint main()\n{\n    const initializer_list<Point> points =  { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };\n    const Figure square = { \"Square\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }\n    };\n\n    const Figure square_hole = { \"Square hole\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},\n           {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure strange = { \"Strange\",\n        {  {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},\n           {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure exagon = { \"Exagon\",\n        {  {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},\n           {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}\n        }\n    };\n\n    for(auto f : {square, square_hole, strange, exagon})\n        f.check(points, cout);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43589, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n"}
{"id": 43590, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n"}
{"id": 43591, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "C++": "#include <iostream>\n#include <string>\n\n\nint countSubstring(const std::string& str, const std::string& sub)\n{\n    if (sub.length() == 0) return 0;\n    int count = 0;\n    for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n    {\n        ++count;\n    }\n    return count;\n}\n\nint main()\n{\n    std::cout << countSubstring(\"the three truths\", \"th\")    << '\\n';\n    std::cout << countSubstring(\"ababababab\", \"abab\")        << '\\n';\n    std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n    return 0;\n}\n"}
{"id": 43592, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n"}
{"id": 43593, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n"}
{"id": 43594, "name": "String comparison", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <string>\n\ntemplate <typename T>\nvoid demo_compare(const T &a, const T &b, const std::string &semantically) {\n    std::cout << a << \" and \" << b << \" are \" << ((a == b) ? \"\" : \"not \")\n              << \"exactly \" << semantically << \" equal.\" << std::endl;\n\n    std::cout << a << \" and \" << b << \" are \" << ((a != b) ? \"\" : \"not \")\n              << semantically << \"inequal.\" << std::endl;\n\n    std::cout << a << \" is \" << ((a < b) ? \"\" : \"not \") << semantically\n              << \" ordered before \" << b << '.' << std::endl;\n\n    std::cout << a << \" is \" << ((a > b) ? \"\" : \"not \") << semantically\n              << \" ordered after \" << b << '.' << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n    \n    std::string a((argc > 1) ? argv[1] : \"1.2.Foo\");\n    std::string b((argc > 2) ? argv[2] : \"1.3.Bar\");\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    std::transform(a.begin(), a.end(), a.begin(), ::tolower);\n    std::transform(b.begin(), b.end(), b.begin(), ::tolower);\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    \n    double numA, numB;\n    std::istringstream(a) >> numA;\n    std::istringstream(b) >> numB;\n    demo_compare<double>(numA, numB, \"numerically\");\n    return (a == b);\n}\n"}
{"id": 43595, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "C++": "#include <fstream>\n#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char **argv)\n{\n\tif(argc>1)\n\t{\n\t\tofstream Notes(note_file, ios::app);\n\t\ttime_t timer = time(NULL);\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\tNotes << asctime(localtime(&timer)) << '\\t';\n\t\t\tfor(int i=1;i<argc;i++)\n\t\t\t\tNotes << argv[i] << ' ';\n\t\t\tNotes << endl;\n\t\t\tNotes.close();\n\t\t}\n\t}\n\telse\n\t{\n\t\tifstream Notes(note_file, ios::in);\n\t\tstring line;\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\twhile(!Notes.eof())\n\t\t\t{\n\t\t\t\tgetline(Notes, line);\n\t\t\t\tcout << line << endl;\n\t\t\t}\n\t\t\tNotes.close();\n\t\t}\n\t}\n}\n"}
{"id": 43596, "name": "Thiele's interpolation formula", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n", "C++": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string.h>\n\nconstexpr unsigned int N = 32u;\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\nconstexpr unsigned int N2 = N * (N - 1u) / 2u;\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\ndouble ρ(double *x, double *y, double *r, int i, int n) {\n    if (n < 0)\n        return 0;\n    if (!n)\n        return y[i];\n\n    unsigned int idx = (N - 1 - n) * (N - n) / 2 + i;\n    if (r[idx] != r[idx])\n        r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2);\n    return r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, unsigned int n) {\n    return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\ninline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); }\ninline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); }\ninline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); }\n\nint main() {\n    constexpr double step = .05;\n    for (auto i = 0u; i < N; i++) {\n        xval[i] = i * step;\n        t_sin[i] = sin(xval[i]);\n        t_cos[i] = cos(xval[i]);\n        t_tan[i] = t_sin[i] / t_cos[i];\n    }\n    for (auto i = 0u; i < N2; i++)\n        r_sin[i] = r_cos[i] = r_tan[i] = NAN;\n\n    std::cout << std::setw(16) << std::setprecision(25)\n              << 6 * i_sin(.5) << std::endl\n              << 3 * i_cos(.5) << std::endl\n              << 4 * i_tan(1.) << std::endl;\n\n    return 0;\n}\n"}
{"id": 43597, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n"}
{"id": 43598, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n"}
{"id": 43599, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n"}
{"id": 43600, "name": "Angles (geometric), normalization and conversion", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n", "C++": "#include <functional>\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <sstream>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n\ntemplate<typename T>\nT normalize(T a, double b) { return std::fmod(a, b); }\n\ninline double d2d(double a) { return normalize<double>(a, 360); }\ninline double g2g(double a) { return normalize<double>(a, 400); }\ninline double m2m(double a) { return normalize<double>(a, 6400); }\ninline double r2r(double a) { return normalize<double>(a, 2*M_PI); }\n\ndouble d2g(double a) { return g2g(a * 10 / 9); }\ndouble d2m(double a) { return m2m(a * 160 / 9); }\ndouble d2r(double a) { return r2r(a * M_PI / 180); }\ndouble g2d(double a) { return d2d(a * 9 / 10); }\ndouble g2m(double a) { return m2m(a * 16); }\ndouble g2r(double a) { return r2r(a * M_PI / 200); }\ndouble m2d(double a) { return d2d(a * 9 / 160); }\ndouble m2g(double a) { return g2g(a / 16); }\ndouble m2r(double a) { return r2r(a * M_PI / 3200); }\ndouble r2d(double a) { return d2d(a * 180 / M_PI); }\ndouble r2g(double a) { return g2g(a * 200 / M_PI); }\ndouble r2m(double a) { return m2m(a * 3200 / M_PI); }\n\nvoid print(const std::vector<double> &values, const char *s, std::function<double(double)> f) {\n    using namespace std;\n    ostringstream out;\n    out << \"                  ┌───────────────────┐\\n\";\n    out << \"                  │ \" << setw(17) << s << \" │\\n\";\n    out << \"┌─────────────────┼───────────────────┤\\n\";\n    for (double i : values)\n        out << \"│ \" << setw(15) << fixed << i << defaultfloat << \" │ \" << setw(17) << fixed << f(i) << defaultfloat << \" │\\n\";\n    out << \"└─────────────────┴───────────────────┘\\n\";\n    auto str = out.str();\n    boost::algorithm::replace_all(str, \".000000\", \"       \");\n    cout << str;\n}\n\nint main() {\n    std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 };\n    print(values, \"normalized (deg)\", d2d);\n    print(values, \"normalized (grad)\", g2g);\n    print(values, \"normalized (mil)\", m2m);\n    print(values, \"normalized (rad)\", r2r);\n\n    print(values, \"deg -> grad \", d2g);\n    print(values, \"deg -> mil \", d2m);\n    print(values, \"deg -> rad \", d2r);\n\n    print(values, \"grad -> deg \", g2d);\n    print(values, \"grad -> mil \", g2m);\n    print(values, \"grad -> rad \", g2r);\n\n    print(values, \"mil -> deg \", m2d);\n    print(values, \"mil -> grad \", m2g);\n    print(values, \"mil -> rad \", m2r);\n\n    print(values, \"rad -> deg \", r2d);\n    print(values, \"rad -> grad \", r2g);\n    print(values, \"rad -> mil \", r2m);\n\n    return 0;\n}\n"}
{"id": 43601, "name": "Find common directory path", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::string longestPath( const std::vector<std::string> & , char ) ;\n\nint main( ) {\n   std::string dirs[ ] = {\n      \"/home/user1/tmp/coverage/test\" ,\n      \"/home/user1/tmp/covert/operator\" ,\n      \"/home/user1/tmp/coven/members\" } ;\n   std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;\n   std::cout << \"The longest common path of the given directories is \"\n             << longestPath( myDirs , '/' ) << \"!\\n\" ;\n   return 0 ;\n}\n\nstd::string longestPath( const std::vector<std::string> & dirs , char separator ) {\n   std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;\n   int maxCharactersCommon = vsi->length( ) ;\n   std::string compareString = *vsi ;\n   for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {\n      std::pair<std::string::const_iterator , std::string::const_iterator> p = \n\t std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;\n      if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) \n\t maxCharactersCommon = p.first - compareString.begin( ) ;\n   }\n   std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;\n   return compareString.substr( 0 , found ) ;\n}\n"}
{"id": 43602, "name": "Verify distribution uniformity_Naive", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n", "C++": "#include <map>\n#include <iostream>\n#include <cmath>\n\ntemplate<typename F>\n bool test_distribution(F f, int calls, double delta)\n{\n  typedef std::map<int, int> distmap;\n  distmap dist;\n\n  for (int i = 0; i < calls; ++i)\n    ++dist[f()];\n\n  double mean = 1.0/dist.size();\n\n  bool good = true;\n\n  for (distmap::iterator i = dist.begin(); i != dist.end(); ++i)\n  {\n    if (std::abs((1.0 * i->second)/calls - mean) > delta)\n    {\n      std::cout << \"Relative frequency \" << i->second/(1.0*calls)\n                << \" of result \" << i->first\n                << \" deviates by more than \" << delta\n                << \" from the expected value \" << mean << \"\\n\";\n      good = false;\n    }\n  }\n\n  return good;\n}\n"}
{"id": 43603, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n"}
{"id": 43604, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n"}
{"id": 43605, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n"}
{"id": 43606, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n"}
{"id": 43607, "name": "Memory allocation", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n", "C++": "#include <string>\n\nint main()\n{\n  int* p;\n\n  p = new int;    \n  delete p;       \n\n  p = new int(2); \n  delete p;       \n\n  std::string* p2;\n\n  p2 = new std::string; \n  delete p2;            \n\n  p = new int[10]; \n  delete[] p;      \n\n  p2 = new std::string[10]; \n  delete[] p2;              \n}\n"}
{"id": 43608, "name": "Tic-tac-toe", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum players { Computer, Human, Draw, None };\nconst int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };\n\n\nclass ttt\n{\npublic:\n    ttt() { _p = rand() % 2; reset(); }\n\n    void play()\n    {\n\tint res = Draw;\n\twhile( true )\n\t{\n\t    drawGrid();\n\t    while( true )\n\t    {\n\t\tif( _p ) getHumanMove();\n\t\telse getComputerMove();\n\n\t\tdrawGrid();\n\n\t\tres = checkVictory();\n\t\tif( res != None ) break;\n\n\t\t++_p %= 2;\n\t    }\n\n\t    if( res == Human ) cout << \"CONGRATULATIONS HUMAN --- You won!\";\n\t    else if( res == Computer ) cout << \"NOT SO MUCH A SURPRISE --- I won!\";\n\t    else cout << \"It's a draw!\";\n\n\t    cout << endl << endl;\n\n\t    string r;\n\t    cout << \"Play again( Y / N )? \"; cin >> r;\n\t    if( r != \"Y\" && r != \"y\" ) return;\n\n\t    ++_p %= 2;\n\t    reset();\n\n\t}\n    }\n\nprivate:\n    void reset() \n    {\n\tfor( int x = 0; x < 9; x++ )\n\t    _field[x] = None;\n    }\n\n    void drawGrid()\n    {\n\tsystem( \"cls\" );\n\t\t\n        COORD c = { 0, 2 };\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\n\tcout << \" 1 | 2 | 3 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 4 | 5 | 6 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 7 | 8 | 9 \" << endl << endl << endl;\n\n\tint f = 0;\n\tfor( int y = 0; y < 5; y += 2 )\n\t    for( int x = 1; x < 11; x += 4 )\n\t    {\n\t\tif( _field[f] != None )\n\t\t{\n\t\t    COORD c = { x, 2 + y };\n\t\t    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\t\t    string o = _field[f] == Computer ? \"X\" : \"O\";\n\t\t    cout << o;\n\t\t}\n\t\tf++;\n\t    }\n\n        c.Y = 9;\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n    }\n\n    int checkVictory()\n    {\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    if( _field[iWin[i][0]] != None &&\n\t\t_field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )\n\t    {\n\t\treturn _field[iWin[i][0]];\n\t    }\n\t}\n\n\tint i = 0;\n\tfor( int f = 0; f < 9; f++ )\n\t{\n\t    if( _field[f] != None )\n\t\ti++;\n\t}\n\tif( i == 9 ) return Draw;\n\n\treturn None;\n    }\n\n    void getHumanMove()\n    {\n\tint m;\n\tcout << \"Enter your move ( 1 - 9 ) \";\n\twhile( true )\n\t{\n\t    m = 0;\n\t    do\n\t    { cin >> m; }\n\t    while( m < 1 && m > 9 );\n\n\t    if( _field[m - 1] != None )\n\t\tcout << \"Invalid move. Try again!\" << endl;\n\t    else break;\n\t}\n\n\t_field[m - 1] = Human;\n    }\n\n    void getComputerMove()\n    {\n\tint move = 0;\n\n\tdo{ move = rand() % 9; }\n\twhile( _field[move] != None );\n\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];\n\n\t    if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )\n\t    {\n\t\tmove = try3;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) \n\t    {\t\t\t\n\t\tmove = try2;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )\n\t    {\n\t\tmove = try1;\n\t\tif( _field[try2] == Computer ) break;\n\t    }\n        }\n\t_field[move] = Computer;\n\t\t\n    }\n\n\nint _p;\nint _field[9];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n\n    ttt tic;\n    tic.play();\n\n    return 0;\n}\n\n"}
{"id": 43609, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n"}
{"id": 43610, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n"}
{"id": 43611, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n"}
{"id": 43612, "name": "Entropy_Narcissist", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n", "C++": "#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\n\nstring readFile (string path) {\n    string contents;\n    string line;\n    ifstream inFile(path);\n    while (getline (inFile, line)) {\n        contents.append(line);\n        contents.append(\"\\n\");\n    }\n    inFile.close();\n    return contents;\n}\n\ndouble entropy (string X) {\n    const int MAXCHAR = 127;\n    int N = X.length();\n    int count[MAXCHAR];\n    double count_i;\n    char ch;\n    double sum = 0.0;\n    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;\n    for (int pos = 0; pos < N; pos++) {\n        ch = X[pos];\n        count[(int)ch]++;\n    }\n    for (int n_i = 0; n_i < MAXCHAR; n_i++) {\n        count_i = count[n_i];\n        if (count_i > 0) sum -= count_i / N * log2(count_i / N);\n    }\n    return sum;\n}\n\nint main () {\n    cout<<entropy(readFile(\"entropy.cpp\"));\n    return 0;\n}\n"}
{"id": 43613, "name": "Bitwise operations", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n"}
{"id": 43614, "name": "Dragon curve", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n"}
{"id": 43615, "name": "Read a file line by line", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n"}
{"id": 43616, "name": "Doubly-linked list_Element insertion", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n"}
{"id": 43617, "name": "Quickselect algorithm", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43618, "name": "Quickselect algorithm", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43619, "name": "Non-decimal radices_Convert", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n"}
{"id": 43620, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n"}
{"id": 43621, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 43622, "name": "Classes", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n"}
{"id": 43623, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 43624, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 43625, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 43626, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 43627, "name": "Hofstadter Figure-Figure sequences", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 43628, "name": "Anonymous recursion", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 43629, "name": "Create a file", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n"}
{"id": 43630, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n"}
{"id": 43631, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n"}
{"id": 43632, "name": "Sum of divisors", "C#": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 43633, "name": "Bacon cipher", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 43634, "name": "Bacon cipher", "C#": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 43635, "name": "Bacon cipher", "C#": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 43636, "name": "Spiral matrix", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 43637, "name": "Faulhaber's triangle", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n"}
{"id": 43638, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43639, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43640, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n"}
{"id": 43641, "name": "User input_Text", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43642, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 43643, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 43644, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 43645, "name": "Cartesian product of two or more lists", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 43646, "name": "First-class functions", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n"}
{"id": 43647, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 43648, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 43649, "name": "XML_Output", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n"}
{"id": 43650, "name": "Regular expressions", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n"}
{"id": 43651, "name": "Guess the number_With feedback (player)", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n"}
{"id": 43652, "name": "Guess the number_With feedback (player)", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n"}
{"id": 43653, "name": "Hash from two arrays", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n"}
{"id": 43654, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43655, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43656, "name": "Bin given limits", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43657, "name": "Animate a pendulum", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 43658, "name": "Animate a pendulum", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 43659, "name": "Sorting algorithms_Heapsort", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 43660, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n"}
{"id": 43661, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 43662, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 43663, "name": "Sierpinski carpet", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43664, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n"}
{"id": 43665, "name": "Merge and aggregate datasets", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n"}
{"id": 43666, "name": "Euler method", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n"}
{"id": 43667, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 43668, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 43669, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43670, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43671, "name": "JortSort", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n"}
{"id": 43672, "name": "Leap year", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n"}
{"id": 43673, "name": "Sort numbers lexicographically", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n"}
{"id": 43674, "name": "Number names", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n"}
{"id": 43675, "name": "Compare length of two strings", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43676, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 43677, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 43678, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n"}
{"id": 43679, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 43680, "name": "Averages_Arithmetic mean", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 43681, "name": "Entropy", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 43682, "name": "Tokenize a string with escaping", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n"}
{"id": 43683, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n"}
{"id": 43684, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n"}
{"id": 43685, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n"}
{"id": 43686, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n"}
{"id": 43687, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n"}
{"id": 43688, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n"}
{"id": 43689, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n"}
{"id": 43690, "name": "Singly-linked list_Traversal", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n"}
{"id": 43691, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43692, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 43693, "name": "Delete a file", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n"}
{"id": 43694, "name": "Discordian date", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n"}
{"id": 43695, "name": "Discordian date", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n"}
{"id": 43696, "name": "Average loop length", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 43697, "name": "Bitwise operations", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 43698, "name": "Dragon curve", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n"}
{"id": 43699, "name": "Read a file line by line", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 43700, "name": "Doubly-linked list_Element insertion", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n"}
{"id": 43701, "name": "Quickselect algorithm", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n"}
{"id": 43702, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 43703, "name": "Walk a directory_Recursively", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 43704, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 43705, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 43706, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 43707, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 43708, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 43709, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 43710, "name": "LZW compression", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n"}
{"id": 43711, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 43712, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 43713, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 43714, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 43715, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 43716, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 43717, "name": "Anonymous recursion", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 43718, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 43719, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 43720, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 43721, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 43722, "name": "Longest string challenge", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n"}
{"id": 43723, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 43724, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 43725, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 43726, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 43727, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 43728, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 43729, "name": "Dining philosophers", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n"}
{"id": 43730, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 43731, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 43732, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 43733, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 43734, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 43735, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 43736, "name": "Spiral matrix", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n"}
{"id": 43737, "name": "Optional parameters", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n"}
{"id": 43738, "name": "Call a foreign-language function", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 43739, "name": "Faulhaber's triangle", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n"}
{"id": 43740, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 43741, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 43742, "name": "Word wheel", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n"}
{"id": 43743, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 43744, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 43745, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 43746, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 43747, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 43748, "name": "Primes - allocate descendants to their ancestors", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n"}
{"id": 43749, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 43750, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 43751, "name": "Proper divisors", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 43752, "name": "XML_Output", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n"}
{"id": 43753, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 43754, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 43755, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 43756, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 43757, "name": "Hash from two arrays", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 43758, "name": "Colour pinstripe_Display", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n"}
{"id": 43759, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n"}
{"id": 43760, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n"}
{"id": 43761, "name": "Animate a pendulum", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n"}
{"id": 43762, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 43763, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 43764, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 43765, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 43766, "name": "Arrays", "VB": "Option Base {0|1}\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 43767, "name": "Sierpinski carpet", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 43768, "name": "Sorting algorithms_Bogosort", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 43769, "name": "Euler method", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 43770, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 43771, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 43772, "name": "JortSort", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n"}
{"id": 43773, "name": "Leap year", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 43774, "name": "Combinations and permutations", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n"}
{"id": 43775, "name": "Sort numbers lexicographically", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n"}
{"id": 43776, "name": "Number names", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 43777, "name": "Sorting algorithms_Shell sort", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 43778, "name": "Doubly-linked list_Definition", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n"}
{"id": 43779, "name": "Letter frequency", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 43780, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 43781, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 43782, "name": "Averages_Arithmetic mean", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 43783, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 43784, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 43785, "name": "Tokenize a string with escaping", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n"}
{"id": 43786, "name": "Tokenize a string with escaping", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n"}
{"id": 43787, "name": "Hello world_Text", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n"}
{"id": 43788, "name": "Forward difference", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 43789, "name": "Primality by trial division", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 43790, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 43791, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 43792, "name": "Singly-linked list_Traversal", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 43793, "name": "Singly-linked list_Traversal", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 43794, "name": "Bitmap_Write a PPM file", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 43795, "name": "Delete a file", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 43796, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 43797, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 43798, "name": "String interpolation (included)", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 43799, "name": "Determinant and permanent", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 43800, "name": "Determinant and permanent", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 43801, "name": "Ray-casting algorithm", "VB": "Imports System.Math\n\nModule RayCasting\n\n    Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}\n    Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}\n    Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}\n    Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}\n    Private shapes As Integer()()() = {square, squareHole, strange, hexagon}\n\n    Public Sub Main()\n        Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}\n\n        For Each shape As Integer()() In shapes\n            For Each point As Double() In testPoints\n                Console.Write(String.Format(\"{0} \", Contains(shape, point).ToString.PadLeft(7)))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\n    Private Function Contains(shape As Integer()(), point As Double()) As Boolean\n\n        Dim inside As Boolean = False\n        Dim length As Integer = shape.Length\n\n        For i As Integer = 0 To length - 1\n            If Intersects(shape(i), shape((i + 1) Mod length), point) Then\n                inside = Not inside\n            End If\n        Next\n\n        Return inside\n    End Function\n\n    Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean\n\n        If a(1) > b(1) Then Return Intersects(b, a, p)\n        If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001\n        If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False\n        If p(0) < Min(a(0), b(0)) Then Return True\n        Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))\n        Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))\n\n        Return red >= blue\n    End Function\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 43802, "name": "Count occurrences of a substring", "VB": "Function CountSubstring(str,substr)\n\tCountSubstring = 0\n\tFor i = 1 To Len(str)\n\t\tIf Len(str) >= Len(substr) Then\n\t\t\tIf InStr(i,str,substr) Then\n\t\t\t\tCountSubstring = CountSubstring + 1\n\t\t\t\ti = InStr(i,str,substr) + Len(substr) - 1\n\t\t\tEnd If\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write CountSubstring(\"the three truths\",\"th\") & vbCrLf\nWScript.StdOut.Write CountSubstring(\"ababababab\",\"abab\") & vbCrLf\n", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n"}
{"id": 43803, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 43804, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 43805, "name": "Take notes on the command line", "VB": "Imports System.IO\n\nModule Notes\n    Function Main(ByVal cmdArgs() As String) As Integer\n        Try\n            If cmdArgs.Length = 0 Then\n                Using sr As New StreamReader(\"NOTES.TXT\")\n                    Console.WriteLine(sr.ReadToEnd)\n                End Using\n            Else\n                Using sw As New StreamWriter(\"NOTES.TXT\", True)\n                    sw.WriteLine(Date.Now.ToString())\n                    sw.WriteLine(\"{0}{1}\", ControlChars.Tab, String.Join(\" \", cmdArgs))\n                End Using\n            End If\n        Catch\n        End Try\n    End Function\nEnd Module\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 43806, "name": "Find common directory path", "VB": "Public Function CommonDirectoryPath(ParamArray Paths()) As String\nDim v As Variant\nDim Path() As String, s As String\nDim i As Long, j As Long, k As Long\nConst PATH_SEPARATOR As String = \"/\"\n  \n  For Each v In Paths\n    ReDim Preserve Path(0 To i)\n    Path(i) = v\n    i = i + 1\n  Next v\n  \n  k = 1\n  \n  Do\n    For i = 0 To UBound(Path)\n      If i Then\n        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then\n          Exit Do\n        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then\n          Exit Do\n        End If\n      Else\n        j = InStr(k, Path(i), PATH_SEPARATOR)\n        If j = 0 Then\n          Exit Do\n        End If\n      End If\n    Next i\n    s = Left$(Path(0), j + CLng(k <> 1))\n    k = j + 1\n  Loop\n  CommonDirectoryPath = s\n  \nEnd Function\n\nSub Main()\n\n\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/home/user1/tmp\"\n \n Debug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\", _\n \"/home/user1/abc/coven/members\") = _\n \"/home/user1\"\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/hope/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/\"\n\nEnd Sub\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n"}
{"id": 43807, "name": "Verify distribution uniformity_Naive", "VB": "Option Explicit\n\nsub verifydistribution(calledfunction, samples, delta)\n\tDim i, n, maxdiff\n\t\n\tDim d : Set d = CreateObject(\"Scripting.Dictionary\")\n\twscript.echo \"Running \"\"\" & calledfunction & \"\"\" \" & samples & \" times...\"\n\tfor i = 1 to samples\n\t\tExecute \"n = \" & calledfunction\n\t\td(n) = d(n) + 1\n\tnext\n\tn = d.Count\n\tmaxdiff = 0\n\twscript.echo \"Expected average count is \" & Int(samples/n) & \" across \" & n & \" buckets.\"\n\tfor each i in d.Keys\n\t\tdim diff : diff = abs(1 - d(i) / (samples/n))\n\t\tif diff > maxdiff then maxdiff = diff\n\t\twscript.echo \"Bucket \" & i & \" had \" & d(i) & \" occurences\" _\n\t\t& vbTab & \" difference from expected=\" & FormatPercent(diff, 2)\n\tnext\n\twscript.echo \"Maximum found variation is \" & FormatPercent(maxdiff, 2) _\n\t\t& \", desired limit is \" & FormatPercent(delta, 2) & \".\"\n\tif maxdiff > delta then wscript.echo \"Skewed!\" else wscript.echo \"Smooth!\"\nend sub\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 43808, "name": "Stirling numbers of the second kind", "VB": "Imports System.Numerics\n\nModule Module1\n\n    Class Sterling\n        Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)\n\n        Private Shared Function CacheKey(n As Integer, k As Integer) As String\n            Return String.Format(\"{0}:{1}\", n, k)\n        End Function\n\n        Private Shared Function Impl(n As Integer, k As Integer) As BigInteger\n            If n = 0 AndAlso k = 0 Then\n                Return 1\n            End If\n            If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then\n                Return 0\n            End If\n            If n = k Then\n                Return 1\n            End If\n            If k > n Then\n                Return 0\n            End If\n\n            Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)\n        End Function\n\n        Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger\n            Dim key = CacheKey(n, k)\n            If COMPUTED.ContainsKey(key) Then\n                Return COMPUTED(key)\n            End If\n\n            Dim result = Impl(n, k)\n            COMPUTED.Add(key, result)\n            Return result\n        End Function\n    End Class\n\n    Sub Main()\n        Console.WriteLine(\"Stirling numbers of the second kind:\")\n        Dim max = 12\n        Console.Write(\"n/k\")\n        For n = 0 To max\n            Console.Write(\"{0,10}\", n)\n        Next\n        Console.WriteLine()\n        For n = 0 To max\n            Console.Write(\"{0,3}\", n)\n            For k = 0 To n\n                Console.Write(\"{0,10}\", Sterling.Sterling2(n, k))\n            Next\n            Console.WriteLine()\n        Next\n        Console.WriteLine(\"The maximum value of S2(100, k) = \")\n        Dim previous = BigInteger.Zero\n        For k = 1 To 100\n            Dim current = Sterling.Sterling2(100, k)\n            If current > previous Then\n                previous = current\n            Else\n                Console.WriteLine(previous)\n                Console.WriteLine(\"({0} digits, k = {1})\", previous.ToString().Length, k - 1)\n                Exit For\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 43809, "name": "Stirling numbers of the second kind", "VB": "Imports System.Numerics\n\nModule Module1\n\n    Class Sterling\n        Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)\n\n        Private Shared Function CacheKey(n As Integer, k As Integer) As String\n            Return String.Format(\"{0}:{1}\", n, k)\n        End Function\n\n        Private Shared Function Impl(n As Integer, k As Integer) As BigInteger\n            If n = 0 AndAlso k = 0 Then\n                Return 1\n            End If\n            If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then\n                Return 0\n            End If\n            If n = k Then\n                Return 1\n            End If\n            If k > n Then\n                Return 0\n            End If\n\n            Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)\n        End Function\n\n        Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger\n            Dim key = CacheKey(n, k)\n            If COMPUTED.ContainsKey(key) Then\n                Return COMPUTED(key)\n            End If\n\n            Dim result = Impl(n, k)\n            COMPUTED.Add(key, result)\n            Return result\n        End Function\n    End Class\n\n    Sub Main()\n        Console.WriteLine(\"Stirling numbers of the second kind:\")\n        Dim max = 12\n        Console.Write(\"n/k\")\n        For n = 0 To max\n            Console.Write(\"{0,10}\", n)\n        Next\n        Console.WriteLine()\n        For n = 0 To max\n            Console.Write(\"{0,3}\", n)\n            For k = 0 To n\n                Console.Write(\"{0,10}\", Sterling.Sterling2(n, k))\n            Next\n            Console.WriteLine()\n        Next\n        Console.WriteLine(\"The maximum value of S2(100, k) = \")\n        Dim previous = BigInteger.Zero\n        For k = 1 To 100\n            Dim current = Sterling.Sterling2(100, k)\n            If current > previous Then\n                previous = current\n            Else\n                Console.WriteLine(previous)\n                Console.WriteLine(\"({0} digits, k = {1})\", previous.ToString().Length, k - 1)\n                Exit For\n            End If\n        Next\n    End Sub\n\nEnd Module\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 43810, "name": "Recaman's sequence", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 43811, "name": "Recaman's sequence", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 43812, "name": "Tic-tac-toe", "VB": "Option Explicit\n\nPrivate Lines(1 To 3, 1 To 3) As String\nPrivate Nb As Byte, player As Byte\nPrivate GameWin As Boolean, GameOver As Boolean\n\nSub Main_TicTacToe()\nDim p As String\n\n    InitLines\n    printLines Nb\n    Do\n        p = WhoPlay\n        Debug.Print p & \" play\"\n        If p = \"Human\" Then\n            Call HumanPlay\n            GameWin = IsWinner(\"X\")\n        Else\n            Call ComputerPlay\n            GameWin = IsWinner(\"O\")\n        End If\n        If Not GameWin Then GameOver = IsEnd\n    Loop Until GameWin Or GameOver\n    If Not GameOver Then\n        Debug.Print p & \" Win !\"\n    Else\n        Debug.Print \"Game Over!\"\n    End If\nEnd Sub\n\nSub InitLines(Optional S As String)\nDim i As Byte, j As Byte\n    Nb = 0: player = 0\n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            Lines(i, j) = \"#\"\n        Next j\n    Next i\nEnd Sub\n\nSub printLines(Nb As Byte)\nDim i As Byte, j As Byte, strT As String\n    Debug.Print \"Loop \" & Nb\n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            strT = strT & Lines(i, j)\n        Next j\n        Debug.Print strT\n        strT = vbNullString\n    Next i\nEnd Sub\n\nFunction WhoPlay(Optional S As String) As String\n    If player = 0 Then\n        player = 1\n        WhoPlay = \"Human\"\n    Else\n        player = 0\n        WhoPlay = \"Computer\"\n    End If\nEnd Function\n\nSub HumanPlay(Optional S As String)\nDim L As Byte, C As Byte, GoodPlay As Boolean\n\n    Do\n        L = Application.InputBox(\"Choose the row\", \"Numeric only\", Type:=1)\n        If L > 0 And L < 4 Then\n            C = Application.InputBox(\"Choose the column\", \"Numeric only\", Type:=1)\n            If C > 0 And C < 4 Then\n                If Lines(L, C) = \"#\" And Not Lines(L, C) = \"X\" And Not Lines(L, C) = \"O\" Then\n                    Lines(L, C) = \"X\"\n                    Nb = Nb + 1\n                    printLines Nb\n                    GoodPlay = True\n                End If\n            End If\n        End If\n    Loop Until GoodPlay\nEnd Sub\n\nSub ComputerPlay(Optional S As String)\nDim L As Byte, C As Byte, GoodPlay As Boolean\n\n    Randomize Timer\n    Do\n        L = Int((Rnd * 3) + 1)\n        C = Int((Rnd * 3) + 1)\n        If Lines(L, C) = \"#\" And Not Lines(L, C) = \"X\" And Not Lines(L, C) = \"O\" Then\n            Lines(L, C) = \"O\"\n            Nb = Nb + 1\n            printLines Nb\n            GoodPlay = True\n        End If\n    Loop Until GoodPlay\nEnd Sub\n\nFunction IsWinner(S As String) As Boolean\nDim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String\n\n    Ch = String(UBound(Lines, 1), S)\n    \n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            strTL = strTL & Lines(i, j)\n            strTC = strTC & Lines(j, i)\n        Next j\n        If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For\n        strTL = vbNullString: strTC = vbNullString\n    Next i\n    \n    strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3)\n    strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1)\n    If strTL = Ch Or strTC = Ch Then IsWinner = True\nEnd Function\n\nFunction IsEnd() As Boolean\nDim i As Byte, j As Byte\n\n    For i = LBound(Lines, 1) To UBound(Lines, 1)\n        For j = LBound(Lines, 2) To UBound(Lines, 2)\n            If Lines(i, j) = \"#\" Then Exit Function\n        Next j\n    Next i\n    IsEnd = True\nEnd Function\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n"}
{"id": 43813, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n"}
{"id": 43814, "name": "Dragon curve", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n"}
{"id": 43815, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n"}
{"id": 43816, "name": "Doubly-linked list_Element insertion", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n"}
{"id": 43817, "name": "Smarandache prime-digital sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nusing integer = uint32_t;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (integer w : wheel) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += w;\n        }\n    }\n}\n\nint main() {\n    std::cout.imbue(std::locale(\"\"));\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    std::cout << \"First 25 SPDS primes:\\n\";\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                std::cout << ' ';\n            std::cout << n;\n        }\n        else if (i == 25)\n            std::cout << '\\n';\n        ++i;\n        if (i == 100)\n            std::cout << \"Hundredth SPDS prime: \" << n << '\\n';\n        else if (i == 1000)\n            std::cout << \"Thousandth SPDS prime: \" << n << '\\n';\n        else if (i == 10000)\n            std::cout << \"Ten thousandth SPDS prime: \" << n << '\\n';\n        max = n;\n    }\n    std::cout << \"Largest SPDS prime less than \" << limit << \": \" << max << '\\n';\n    return 0;\n}\n"}
{"id": 43818, "name": "Quickselect algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 43819, "name": "Quickselect algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 43820, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n"}
{"id": 43821, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n"}
{"id": 43822, "name": "Main step of GOST 28147-89", "Go": "package main\n\nimport \"fmt\"\n\ntype sBox [8][16]byte\n\ntype gost struct {\n    k87, k65, k43, k21 [256]byte\n    enc                []byte\n}\n\nfunc newGost(s *sBox) *gost {\n    var g gost\n    for i := range g.k87 {\n        g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]\n        g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]\n        g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]\n        g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]\n    }\n    g.enc = make([]byte, 8)\n    return &g\n}\n\nfunc (g *gost) f(x uint32) uint32 {\n    x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |\n        uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])\n    return x<<11 | x>>(32-11)\n}\n\n\n\n\n\n\nvar cbrf = sBox{\n    {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},\n    {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},\n    {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},\n    {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},\n    {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},\n    {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},\n    {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},\n    {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},\n}\n\nfunc u32(b []byte) uint32 {\n    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc b4(u uint32, b []byte) {\n    b[0] = byte(u)\n    b[1] = byte(u >> 8)\n    b[2] = byte(u >> 16)\n    b[3] = byte(u >> 24)\n}\n\nfunc (g *gost) mainStep(input []byte, key []byte) {\n    key32 := u32(key)\n    input1 := u32(input[:4])\n    input2 := u32(input[4:])\n    b4(g.f(key32+input1)^input2, g.enc[:4])\n    copy(g.enc[4:], input[:4])\n}\n\nfunc main() {\n    input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}\n    key := []byte{0xF9, 0x04, 0xC1, 0xE2}\n\n    g := newGost(&cbrf)\n    g.mainStep(input, key)\n    for _, b := range g.enc {\n        fmt.Printf(\"[%02x]\", b)\n    }\n    fmt.Println()\n}\n", "C++": "UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)\n{\n    UINT_64 N;\n\tN = N1;\n\tN = (N<<32)|N2;\n\treturn UINT_64(N);\n}\n\nUINT_32 TGost::ReplaceBlock(UINT_32 x)\n{   \n    register i;\n    UINT_32 res = 0UL;\n    for(i=7;i>=0;i--)\n    {\n       ui4_0 = x>>(i*4);\n       ui4_0 = BS[ui4_0][i];\n       res = (res<<4)|ui4_0;\n    }\n    return res;\n}\n\nUINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)\n{\n   UINT_32 N1,N2,S=0UL;\n   N1=UINT_32(N);\n   N2=N>>32;\n   S = N1 + X % 0x4000000000000;\n   S = ReplaceBlock(S);\n   S = (S<<11)|(S>>21);\n   S ^= N2;\n   N2 = N1;\n   N1 = S;\n   return SWAP32(N2,N1);\n}\n"}
{"id": 43823, "name": "State name puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n\ntemplate<typename T>\nT unique(T&& src)\n{\n    T retval(std::move(src));\n    std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());\n    retval.erase(std::unique(retval.begin(), retval.end()), retval.end());\n    return retval;\n}\n\n#define USE_FAKES 1\n\nauto states = unique(std::vector<std::string>({\n#if USE_FAKES\n    \"Slender Dragon\", \"Abalamara\",\n#endif\n    \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n}));\n\nstruct counted_pair\n{\n    std::string name;\n    std::array<int, 26> count{};\n\n    void count_characters(const std::string& s)\n    {\n        for (auto&& c : s) {\n            if (c >= 'a' && c <= 'z') count[c - 'a']++;\n            if (c >= 'A' && c <= 'Z') count[c - 'A']++;\n        }\n    }\n\n    counted_pair(const std::string& s1, const std::string& s2)\n        : name(s1 + \" + \" + s2)\n    {\n        count_characters(s1);\n        count_characters(s2);\n    }\n};\n\nbool operator<(const counted_pair& lhs, const counted_pair& rhs)\n{\n    auto lhs_size = lhs.name.size();\n    auto rhs_size = rhs.name.size();\n    return lhs_size == rhs_size\n            ? std::lexicographical_compare(lhs.count.begin(),\n                                           lhs.count.end(),\n                                           rhs.count.begin(),\n                                           rhs.count.end())\n            : lhs_size < rhs_size;\n}\n\nbool operator==(const counted_pair& lhs, const counted_pair& rhs)\n{\n    return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;\n}\n\nint main()\n{\n    const int n_states = states.size();\n\n    std::vector<counted_pair> pairs;\n    for (int i = 0; i < n_states; i++) {\n        for (int j = 0; j < i; j++) {\n            pairs.emplace_back(counted_pair(states[i], states[j]));\n        }\n    }\n    std::sort(pairs.begin(), pairs.end());\n\n    auto start = pairs.begin();\n    while (true) {\n        auto match = std::adjacent_find(start, pairs.end());\n        if (match == pairs.end()) {\n            break;\n        }\n        auto next = match + 1;\n        std::cout << match->name << \" => \" << next->name << \"\\n\";\n        start = next;\n    }\n}\n"}
{"id": 43824, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n"}
{"id": 43825, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 43826, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 43827, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n"}
{"id": 43828, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43829, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43830, "name": "LZW compression", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n"}
{"id": 43831, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 43832, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 43833, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 43834, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 43835, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43836, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "C++": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n    integer next() {\n        n2_ = n1_;\n        n1_ = n_;\n        if (n_ < 3) {\n            ++n_;\n        } else {\n            for (n_ = min_; !(sequence_.count(n_) == 0\n                && std::gcd(n1_, n_) == 1\n                && std::gcd(n2_, n_) > 1); ++n_) {}\n        }\n        sequence_.insert(n_);\n        for (;;) {\n            auto it = sequence_.find(min_);\n            if (it == sequence_.end())\n                break;\n            sequence_.erase(it);\n            ++min_;\n        }\n        return n_;\n    }\nprivate:\n    std::set<integer> sequence_;\n    integer min_ = 1;\n    integer n_ = 0;\n    integer n1_ = 0;\n    integer n2_ = 0;\n};\n\nint main() {\n    std::cout << \"First 30 Yellowstone numbers:\\n\";\n    yellowstone_generator<unsigned int> ygen;\n    std::cout << ygen.next();\n    for (int i = 1; i < 30; ++i)\n        std::cout << ' ' << ygen.next();\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43837, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 43838, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 43839, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <stack>\n#include <vector>\n\nconst std::array<std::pair<int, int>, 4> DIRS = {\n    std::make_pair(0, -1),\n    std::make_pair(-1,  0),\n    std::make_pair(0,  1),\n    std::make_pair(1,  0),\n};\n\nvoid printResult(const std::vector<std::vector<int>> &v) {\n    for (auto &row : v) {\n        auto it = row.cbegin();\n        auto end = row.cend();\n\n        std::cout << '[';\n        if (it != end) {\n            std::cout << *it;\n            it = std::next(it);\n        }\n        while (it != end) {\n            std::cout << \", \" << *it;\n            it = std::next(it);\n        }\n        std::cout << \"]\\n\";\n    }\n}\n\nvoid cutRectangle(int w, int h) {\n    if (w % 2 == 1 && h % 2 == 1) {\n        return;\n    }\n\n    std::vector<std::vector<int>> grid(h, std::vector<int>(w));\n    std::stack<int> stack;\n\n    int half = (w * h) / 2;\n    long bits = (long)pow(2, half) - 1;\n\n    for (; bits > 0; bits -= 2) {\n        for (int i = 0; i < half; i++) {\n            int r = i / w;\n            int c = i % w;\n            grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n            grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n        }\n\n        stack.push(0);\n        grid[0][0] = 2;\n        int count = 1;\n        while (!stack.empty()) {\n            int pos = stack.top();\n            stack.pop();\n\n            int r = pos / w;\n            int c = pos % w;\n            for (auto dir : DIRS) {\n                int nextR = r + dir.first;\n                int nextC = c + dir.second;\n\n                if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n                    if (grid[nextR][nextC] == 1) {\n                        stack.push(nextR * w + nextC);\n                        grid[nextR][nextC] = 2;\n                        count++;\n                    }\n                }\n            }\n        }\n        if (count == half) {\n            printResult(grid);\n            std::cout << '\\n';\n        }\n    }\n}\n\nint main() {\n    cutRectangle(2, 2);\n    cutRectangle(4, 3);\n\n    return 0;\n}\n"}
{"id": 43840, "name": "Mertens function", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> mertens_numbers(int max) {\n    std::vector<int> m(max + 1, 1);\n    for (int n = 2; n <= max; ++n) {\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n / k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    auto m(mertens_numbers(max));\n    std::cout << \"First 199 Mertens numbers:\\n\";\n    for (int i = 0, column = 0; i < 200; ++i) {\n        if (column > 0)\n            std::cout << ' ';\n        if (i == 0)\n            std::cout << \"  \";\n        else\n            std::cout << std::setw(2) << m[i];\n        ++column;\n        if (column == 20) {\n            std::cout << '\\n';\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        if (m[i] == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m[i];\n    }\n    std::cout << \"M(n) is zero \" << zero << \" times for 1 <= n <= 1000.\\n\";\n    std::cout << \"M(n) crosses zero \" << cross << \" times for 1 <= n <= 1000.\\n\";\n    return 0;\n}\n"}
{"id": 43841, "name": "Order by pair comparisons", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool InteractiveCompare(const string& s1, const string& s2)\n{\n    if(s1 == s2) return false;  \n    static int count = 0;\n    string response;\n    cout << \"(\" << ++count << \") Is \" << s1 << \" < \" << s2 << \"? \";\n    getline(cin, response);\n    return !response.empty() && response.front() == 'y';\n}\n\nvoid PrintOrder(const vector<string>& items)\n{\n    cout << \"{ \";\n    for(auto& item : items) cout << item << \" \";\n    cout << \"}\\n\";\n}\n\nint main()\n{\n    const vector<string> items\n    {\n        \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n    \n    vector<string> sortedItems;\n    \n    \n    \n    for(auto& item : items)\n    {\n        cout << \"Inserting '\" << item << \"' into \";\n        PrintOrder(sortedItems);\n        \n        \n        auto spotToInsert = lower_bound(sortedItems.begin(),\n                                        sortedItems.end(), item, InteractiveCompare);\n        sortedItems.insert(spotToInsert, item);\n    }\n    PrintOrder(sortedItems);\n    return 0;\n}\n"}
{"id": 43842, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 43843, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 43844, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 43845, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <windows.h>\n\n\nusing namespace std;\n\n\nclass bells\n{\npublic:\n    void start()\n    {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] =  \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n    }\nprivate:\n    static DWORD WINAPI bell( LPVOID p )\n    {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t    Sleep( wait );\n\t    _inst->playBell();\n\t    wait = _inst->waitTime();\n\t}\n\treturn 0;\n    }\n\n    DWORD waitTime() \n    { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n    }\n\n    void playBell()\n    {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t    cout << \"\\7\"; Sleep( 500 );\n\t    if( !( c % 2 ) ) Sleep( 300 );\n\t}\n    }\n\n    SYSTEMTIME st;\n    string watch[7], count[8];\n    static bells* _inst;\n};\n\nbells* bells::_inst = 0;\n\nint main( int argc, char* argv[] )\n{\n    bells b; b.start();\n    while( 1 ); \n    return 0;\n}\n\n"}
{"id": 43846, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n"}
{"id": 43847, "name": "Snake", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"time\"\n\n\ttermbox \"github.com/nsf/termbox-go\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano())\n\tscore, err := playSnake()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Final score:\", score)\n}\n\ntype snake struct {\n\tbody          []position \n\theading       direction\n\twidth, height int\n\tcells         []termbox.Cell\n}\n\ntype position struct {\n\tX int\n\tY int\n}\n\ntype direction int\n\nconst (\n\tNorth direction = iota\n\tEast\n\tSouth\n\tWest\n)\n\nfunc (p position) next(d direction) position {\n\tswitch d {\n\tcase North:\n\t\tp.Y--\n\tcase East:\n\t\tp.X++\n\tcase South:\n\t\tp.Y++\n\tcase West:\n\t\tp.X--\n\t}\n\treturn p\n}\n\nfunc playSnake() (int, error) {\n\terr := termbox.Init()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer termbox.Close()\n\n\ttermbox.Clear(fg, bg)\n\ttermbox.HideCursor()\n\ts := &snake{\n\t\t\n\t\t\n\t\tbody:  make([]position, 0, 32),\n\t\tcells: termbox.CellBuffer(),\n\t}\n\ts.width, s.height = termbox.Size()\n\ts.drawBorder()\n\ts.startSnake()\n\ts.placeFood()\n\ts.flush()\n\n\tmoveCh, errCh := s.startEventLoop()\n\tconst delay = 125 * time.Millisecond\n\tfor t := time.NewTimer(delay); ; t.Reset(delay) {\n\t\tvar move direction\n\t\tselect {\n\t\tcase err = <-errCh:\n\t\t\treturn len(s.body), err\n\t\tcase move = <-moveCh:\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C \n\t\t\t}\n\t\tcase <-t.C:\n\t\t\tmove = s.heading\n\t\t}\n\t\tif s.doMove(move) {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn len(s.body), err\n}\n\nfunc (s *snake) startEventLoop() (<-chan direction, <-chan error) {\n\tmoveCh := make(chan direction)\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(errCh)\n\t\tfor {\n\t\t\tswitch ev := termbox.PollEvent(); ev.Type {\n\t\t\tcase termbox.EventKey:\n\t\t\t\tswitch ev.Ch { \n\t\t\t\tcase 'w', 'W', 'k', 'K':\n\t\t\t\t\tmoveCh <- North\n\t\t\t\tcase 'a', 'A', 'h', 'H':\n\t\t\t\t\tmoveCh <- West\n\t\t\t\tcase 's', 'S', 'j', 'J':\n\t\t\t\t\tmoveCh <- South\n\t\t\t\tcase 'd', 'D', 'l', 'L':\n\t\t\t\t\tmoveCh <- East\n\t\t\t\tcase 0:\n\t\t\t\t\tswitch ev.Key { \n\t\t\t\t\tcase termbox.KeyArrowUp:\n\t\t\t\t\t\tmoveCh <- North\n\t\t\t\t\tcase termbox.KeyArrowDown:\n\t\t\t\t\t\tmoveCh <- South\n\t\t\t\t\tcase termbox.KeyArrowLeft:\n\t\t\t\t\t\tmoveCh <- West\n\t\t\t\t\tcase termbox.KeyArrowRight:\n\t\t\t\t\t\tmoveCh <- East\n\t\t\t\t\tcase termbox.KeyEsc: \n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase termbox.EventResize:\n\t\t\t\t\n\t\t\t\terrCh <- errors.New(\"terminal resizing unsupported\")\n\t\t\t\treturn\n\t\t\tcase termbox.EventError:\n\t\t\t\terrCh <- ev.Err\n\t\t\t\treturn\n\t\t\tcase termbox.EventInterrupt:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn moveCh, errCh\n}\n\nfunc (s *snake) flush() {\n\ttermbox.Flush()\n\ts.cells = termbox.CellBuffer()\n}\n\nfunc (s *snake) getCellRune(p position) rune {\n\ti := p.Y*s.width + p.X\n\treturn s.cells[i].Ch\n}\nfunc (s *snake) setCell(p position, c termbox.Cell) {\n\ti := p.Y*s.width + p.X\n\ts.cells[i] = c\n}\n\nfunc (s *snake) drawBorder() {\n\tfor x := 0; x < s.width; x++ {\n\t\ts.setCell(position{x, 0}, border)\n\t\ts.setCell(position{x, s.height - 1}, border)\n\t}\n\tfor y := 0; y < s.height-1; y++ {\n\t\ts.setCell(position{0, y}, border)\n\t\ts.setCell(position{s.width - 1, y}, border)\n\t}\n}\n\nfunc (s *snake) placeFood() {\n\tfor {\n\t\t\n\t\tx := rand.Intn(s.width-2) + 1\n\t\ty := rand.Intn(s.height-2) + 1\n\t\tfoodp := position{x, y}\n\t\tr := s.getCellRune(foodp)\n\t\tif r != ' ' {\n\t\t\tcontinue\n\t\t}\n\t\ts.setCell(foodp, food)\n\t\treturn\n\t}\n}\n\nfunc (s *snake) startSnake() {\n\t\n\tx := rand.Intn(s.width/2) + s.width/4\n\ty := rand.Intn(s.height/2) + s.height/4\n\thead := position{x, y}\n\ts.setCell(head, snakeHead)\n\ts.body = append(s.body[:0], head)\n\ts.heading = direction(rand.Intn(4))\n}\n\nfunc (s *snake) doMove(move direction) bool {\n\thead := s.body[len(s.body)-1]\n\ts.setCell(head, snakeBody)\n\thead = head.next(move)\n\ts.heading = move\n\ts.body = append(s.body, head)\n\tr := s.getCellRune(head)\n\ts.setCell(head, snakeHead)\n\tgameOver := false\n\tswitch r {\n\tcase food.Ch:\n\t\ts.placeFood()\n\tcase border.Ch, snakeBody.Ch:\n\t\tgameOver = true\n\t\tfallthrough\n\tcase empty.Ch:\n\t\ts.setCell(s.body[0], empty)\n\t\ts.body = s.body[1:]\n\tdefault:\n\t\tpanic(r)\n\t}\n\ts.flush()\n\treturn gameOver\n}\n\nconst (\n\tfg = termbox.ColorWhite\n\tbg = termbox.ColorBlack\n)\n\n\n\nvar (\n\tempty     = termbox.Cell{Ch: ' ', Bg: bg, Fg: fg}\n\tborder    = termbox.Cell{Ch: '+', Bg: bg, Fg: termbox.ColorBlue}\n\tsnakeBody = termbox.Cell{Ch: '#', Bg: bg, Fg: termbox.ColorGreen}\n\tsnakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold}\n\tfood      = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed}\n)\n", "C++": "#include <windows.h>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nconst int WID = 60, HEI = 30, MAX_LEN = 600;\nenum DIR { NORTH, EAST, SOUTH, WEST };\n\nclass snake {\npublic:\n    snake() {\n        console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( \"Snake\" ); \n        COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );\n        SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );\n        CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );\n    }\n    void play() {\n        std::string a;\n        while( 1 ) {\n            createField(); alive = true;\n            while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }\n            COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );\n            SetConsoleTextAttribute( console, 0x000b );\n            std::cout << \"Play again [Y/N]? \"; std::cin >> a;\n            if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;\n        }\n    }\nprivate:\n    void createField() {\n        COORD coord = { 0, 0 }; DWORD c;\n        FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );\n        FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );\n        SetConsoleCursorPosition( console, coord );\n        int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;\n        for( x = 0; x < WID; x++ ) {\n            brd[x] = brd[x + WID * ( HEI - 1 )] = '+';\n        }\n        for( ; y < HEI; y++ ) {\n            brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';\n        }\n        do {\n            x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n        } while( brd[x + WID * y] );\n        brd[x + WID * y] = '@';\n        tailIdx = 0; headIdx = 4; x = 3; y = 2;\n        for( int c = tailIdx; c < headIdx; c++ ) {\n            brd[x + WID * y] = '#';\n            snk[c].X = 3 + c; snk[c].Y = 2;\n        }\n        head = snk[3]; dir = EAST; points = 0;\n    }\n    void readKey() {\n        if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;\n        if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;\n        if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;\n        if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;\n    }\n    void drawField() {\n        COORD coord; char t;\n        for( int y = 0; y < HEI; y++ ) {\n            coord.Y = y;\n            for( int x = 0; x < WID; x++ ) {\n                t = brd[x + WID * y]; if( !t ) continue;\n                coord.X = x; SetConsoleCursorPosition( console, coord );\n                if( coord.X == head.X && coord.Y == head.Y ) {\n                    SetConsoleTextAttribute( console, 0x002e );\n                    std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );\n                    continue;\n                }\n                switch( t ) {\n                    case '#': SetConsoleTextAttribute( console, 0x002a ); break;\n                    case '+': SetConsoleTextAttribute( console, 0x0019 ); break;\n                    case '@': SetConsoleTextAttribute( console, 0x004c ); break;\n                }\n                std::cout << t; SetConsoleTextAttribute( console, 0x0000 );\n            }\n        }\n        std::cout << t; SetConsoleTextAttribute( console, 0x0007 );\n        COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );\n        std::cout << \"Points: \" << points;\n    }\n    void moveSnake() {\n        switch( dir ) {\n            case NORTH: head.Y--; break;\n            case EAST: head.X++; break;\n            case SOUTH: head.Y++; break;\n            case WEST: head.X--; break;\n        }\n        char t = brd[head.X + WID * head.Y];\n        if( t && t != '@' ) { alive = false; return; }\n        brd[head.X + WID * head.Y] = '#';\n        snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;\n        if( ++headIdx >= MAX_LEN ) headIdx = 0;\n        if( t == '@' ) {\n            points++; int x, y;\n            do {\n                x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );\n            } while( brd[x + WID * y] );\n            brd[x + WID * y] = '@'; return;\n        }\n        SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';\n        brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;\n        if( ++tailIdx >= MAX_LEN ) tailIdx = 0;\n    }\n    bool alive; char brd[WID * HEI]; \n    HANDLE console; DIR dir; COORD snk[MAX_LEN];\n    COORD head; int tailIdx, headIdx, points;\n};\nint main( int argc, char* argv[] ) {\n    srand( static_cast<unsigned>( time( NULL ) ) );\n    snake s; s.play(); return 0;\n}\n"}
{"id": 43848, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43849, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43850, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 43851, "name": "Legendre prime counting function", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> generate_primes(int limit) {\n    std::vector<bool> sieve(limit >> 1, true);\n    for (int p = 3, s = 9; s < limit; p += 2) {\n        if (sieve[p >> 1]) {\n            for (int q = s; q < limit; q += p << 1)\n                sieve[q >> 1] = false;\n        }\n        s += (p + 1) << 2;\n    }\n    std::vector<int> primes;\n    if (limit > 2)\n        primes.push_back(2);\n    for (int i = 1; i < sieve.size(); ++i) {\n        if (sieve[i])\n            primes.push_back((i << 1) + 1);\n    }\n    return primes;\n}\n\nclass legendre_prime_counter {\npublic:\n    explicit legendre_prime_counter(int limit);\n    int prime_count(int n);\nprivate:\n    int phi(int x, int a);\n    std::vector<int> primes;\n};\n\nlegendre_prime_counter::legendre_prime_counter(int limit) :\n    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}\n\nint legendre_prime_counter::prime_count(int n) {\n    if (n < 2)\n        return 0;\n    int a = prime_count(static_cast<int>(std::sqrt(n)));\n    return phi(n, a) + a - 1;\n}\n\nint legendre_prime_counter::phi(int x, int a) {\n    if (a == 0)\n        return x;\n    if (a == 1)\n        return x - (x >> 1);\n    int pa = primes[a - 1];\n    if (x <= pa)\n        return 1;\n    return phi(x, a - 1) - phi(x / pa, a - 1);\n}\n\nint main() {\n    legendre_prime_counter counter(1000000000);\n    for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n        std::cout << \"10^\" << i << \"\\t\" << counter.prime_count(n) << '\\n';\n}\n"}
{"id": 43852, "name": "Use another language to call a function", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n", "C++": "#include <string>\nusing std::string;\n\n\nextern \"C\" int\nQuery (char *Data, size_t *Length)\n{\n   const string Message = \"Here am I\";\n\n   \n   if (*Length < Message.length())\n      return false;  \n\n   *Length = Message.length();\n   Message.copy(Data, *Length);\n   return true;\n}\n"}
{"id": 43853, "name": "Longest string challenge", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n"}
{"id": 43854, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 43855, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 43856, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 43857, "name": "Unprimeable numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n#include \"prime_sieve.hpp\"\n\ntypedef uint32_t integer;\n\n\nint count_digits(integer n) {\n    int digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\ninteger change_digit(integer n, int index, int new_digit) {\n    integer p = 1;\n    integer changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const prime_sieve& sieve, integer n) {\n    if (sieve.is_prime(n))\n        return false;\n    int d = count_digits(n);\n    for (int i = 0; i < d; ++i) {\n        for (int j = 0; j <= 9; ++j) {\n            integer m = change_digit(n, i, j);\n            if (m != n && sieve.is_prime(m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const integer limit = 10000000;\n    prime_sieve sieve(limit);\n\n    \n    std::cout.imbue(std::locale(\"\"));\n\n    std::cout << \"First 35 unprimeable numbers:\\n\";\n    integer n = 100;\n    integer lowest[10] = { 0 };\n    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(sieve, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    std::cout << \", \";\n                std::cout << n;\n            }\n            ++count;\n            if (count == 600)\n                std::cout << \"\\n600th unprimeable number: \" << n << '\\n';\n            int last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    for (int i = 0; i < 10; ++i)\n        std::cout << \"Least unprimeable number ending in \" << i << \": \" << lowest[i] << '\\n';\n    return 0;\n}\n"}
{"id": 43858, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 43859, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "C++": "#include <iostream>\n#include <iomanip>\n\ninline int sign(int i) {\n    return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n    return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n    \n    E(v, 0, 0) = 151;\n    E(v, 2, 0) = 40;\n    E(v, 4, 1) = 11;\n    E(v, 4, 3) = 4;\n\n    \n    for (auto i = 1u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++) {\n            E(diff, i, j) = 0;\n            if (j < i)\n                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n            if (j)\n                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n        }\n\n    for (auto i = 0u; i < 4u; i++)\n        for (auto j = 0u; j < i; j++)\n            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n    \n    uint sum;\n    int e = 0;\n    for (auto i = sum = 0u; i < 15u; i++) {\n        sum += !!sign(e = diff[i]);\n\n        \n        if (e >= 4 || e <= -4)\n            v[i] += e / 5;\n        else if (rand() < RAND_MAX / 4)\n            v[i] += sign(e);\n    }\n    return sum;\n}\n\nvoid show(int *x) {\n    for (auto i = 0u; i < 5u; i++)\n        for (auto j = 0u; j <= i; j++)\n            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n    int v[15] = { 0 }, diff[15] = { 0 };\n    for (auto i = 1u, s = 1u; s; i++) {\n        s = iter(v, diff);\n        std::cout << \"pass \" << i << \": \" << s << std::endl;\n    }\n    show(v);\n\n    return 0;\n}\n"}
{"id": 43860, "name": "Chernick's Carmichael numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n", "C++": "#include <gmp.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef unsigned long long int u64;\n\nbool primality_pretest(u64 k) {     \n\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||\n        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)\n    ) {\n        return (k <= 23);\n    }\n\n    return true;\n}\n\nbool probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nbool is_chernick(int n, u64 m, mpz_t z) {\n\n    if (!primality_pretest(6 * m + 1)) {\n        return false;\n    }\n\n    if (!primality_pretest(12 * m + 1)) {\n        return false;\n    }\n\n    u64 t = 9 * m;\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!primality_pretest((t << i) + 1)) {\n            return false;\n        }\n    }\n\n    if (!probprime(6 * m + 1, z)) {\n        return false;\n    }\n\n    if (!probprime(12 * m + 1, z)) {\n        return false;\n    }\n\n    for (int i = 1; i <= n - 2; i++) {\n        if (!probprime((t << i) + 1, z)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main() {\n\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n++) {\n\n        \n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        \n        if (n > 5) {\n            multiplier *= 5;\n        }\n\n        for (u64 k = 1; ; k++) {\n\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z)) {\n                cout << \"a(\" << n << \") has m = \" << m << endl;\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43861, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 43862, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "C++": "#include <iostream>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n    double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n    double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n    double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    std::cout << \"Triangle is [\";\n    printPoint(x1, y1);\n    std::cout << \", \";\n    printPoint(x2, y2);\n    std::cout << \", \";\n    printPoint(x3, y3);\n    std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    std::cout << \"Point \";\n    printPoint(x, y);\n    std::cout << \" is within triangle? \";\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        std::cout << \"true\\n\";\n    } else {\n        std::cout << \"false\\n\";\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    std::cout << '\\n';\n\n    return 0;\n}\n"}
{"id": 43863, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43864, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(3) << divisor_count(n);\n        if (n % 20 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43865, "name": "Create an object at a given address", "Go": "package main\n\nimport(\n\t\"fmt\"\n\t\"unsafe\"\n\t\"reflect\"\n)\n\nfunc pointer() {\n\tfmt.Printf(\"Pointer:\\n\")\n\n\t\n\t\n\t\n\t\n\tvar i int\n\tp := &i\n\n\tfmt.Printf(\"Before:\\n\\t%v: %v, %v\\n\", p, *p, i)\n\n\t*p = 3\n\n\tfmt.Printf(\"After:\\n\\t%v: %v, %v\\n\", p, *p, i)\n}\n\nfunc slice() {\n\tfmt.Printf(\"Slice:\\n\")\n\n\tvar a [10]byte\n\n\t\n\t\n\t\n\t\n\t\n\tvar h reflect.SliceHeader\n\th.Data = uintptr(unsafe.Pointer(&a)) \n\th.Len = len(a)\n\th.Cap = len(a)\n\n\t\n\ts := *(*[]byte)(unsafe.Pointer(&h))\n\n\tfmt.Printf(\"Before:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n\n\t\n\t\n\tcopy(s, \"A string.\")\n\n\tfmt.Printf(\"After:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n}\n\nfunc main() {\n\tpointer()\n\tfmt.Println()\n\n\tslice()\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main()\n{\n    \n    char* data = new char[sizeof(std::string)];\n\n    \n    std::string* stringPtr = new (data) std::string(\"ABCD\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    \n    stringPtr->~basic_string();\n    stringPtr = new (data) std::string(\"123456\");\n\n    std::cout << *stringPtr << \" 0x\" << stringPtr << std::endl;\n\n    \n    stringPtr->~basic_string();\n    delete[] data;\n}\n"}
{"id": 43866, "name": "Sequence of primorial primes", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <gmpxx.h>\n\ntypedef mpz_class integer;\n\nbool is_probably_prime(const integer& n) {\n    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main() {\n    const unsigned int max = 20;\n    integer primorial = 1;\n    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {\n        if (!is_prime(p))\n            continue;\n        primorial *= p;\n        ++index;\n        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {\n            if (count > 0)\n                std::cout << ' ';\n            std::cout << index;\n            ++count;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43867, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 43868, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 43869, "name": "Dining philosophers", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n"}
{"id": 43870, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 43871, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 43872, "name": "Logistic curve fitting in epidemiology", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n", "C++": "#include <cmath>\n#include <functional>\n#include <iostream>\n\nconstexpr double K = 7.8e9;\nconstexpr int n0 = 27;\nconstexpr double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\n\ndouble f(double r) {\n    double sq = 0;\n    constexpr size_t len = std::size(actual);\n    for (size_t i = 0; i < len; ++i) {\n        double eri = std::exp(r * i);\n        double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {\n    for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n             delta > epsilon && guess != guess - delta;\n             delta *= factor) {\n        double nf = fn(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else\n                factor = 0.5;\n        }\n    }\n    return guess;\n}\n\nint main() {\n    double r = solve(f);\n    double R0 = std::exp(12 * r);\n    std::cout << \"r = \" << r << \", R0 = \" << R0 << '\\n';\n    return 0;\n}\n"}
{"id": 43873, "name": "Sorting algorithms_Strand sort", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n", "C++": "#include <list>\n\ntemplate <typename T>\nstd::list<T> strandSort(std::list<T> lst) {\n  if (lst.size() <= 1)\n    return lst;\n  std::list<T> result;\n  std::list<T> sorted;\n  while (!lst.empty()) {\n    sorted.push_back(lst.front());\n    lst.pop_front();\n    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {\n      if (sorted.back() <= *it) {\n        sorted.push_back(*it);\n        it = lst.erase(it);\n      } else\n        it++;\n    }\n    result.merge(sorted);\n  }\n  return result;\n}\n"}
{"id": 43874, "name": "Additive primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\nbool is_prime(unsigned int n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    for (unsigned int p = 5; p * p <= n; p += 4) {\n        if (n % p == 0)\n            return false;\n        p += 2;\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nunsigned int digit_sum(unsigned int n) {\n    unsigned int sum = 0;\n    for (; n > 0; n /= 10)\n        sum += n % 10;\n    return sum;\n}\n\nint main() {\n    const unsigned int limit = 500;\n    std::cout << \"Additive primes less than \" << limit << \":\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; n < limit; ++n) {\n        if (is_prime(digit_sum(n)) && is_prime(n)) {\n            std::cout << std::setw(3) << n;\n            if (++count % 10 == 0)\n                std::cout << '\\n';\n            else\n                std::cout << ' ';\n        }\n    }\n    std::cout << '\\n' << count << \" additive primes found.\\n\";\n}\n"}
{"id": 43875, "name": "Inverted syntax", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n"}
{"id": 43876, "name": "Inverted syntax", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n", "C++": "class invertedAssign {\n  int data;\npublic:\n  invertedAssign(int data):data(data){}\n  int getData(){return data;}\n  void operator=(invertedAssign& other) const {\n    other.data = this->data;\n  }\n};\n\n\n#include <iostream>\n\nint main(){\n  invertedAssign a = 0;\n  invertedAssign b = 42;\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n  b = a;\n\n  std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}\n"}
{"id": 43877, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43878, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43879, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "C++": "#include <cassert>\n#include <iostream>\n#include <vector>\n\nclass totient_calculator {\npublic:\n    explicit totient_calculator(int max) : totient_(max + 1) {\n        for (int i = 1; i <= max; ++i)\n            totient_[i] = i;\n        for (int i = 2; i <= max; ++i) {\n            if (totient_[i] < i)\n                continue;\n            for (int j = i; j <= max; j += i)\n                totient_[j] -= totient_[j] / i;\n        }\n    }\n    int totient(int n) const {\n        assert (n >= 1 && n < totient_.size());\n        return totient_[n];\n    }\n    bool is_prime(int n) const {\n        return totient(n) == n - 1;\n    }\nprivate:\n    std::vector<int> totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n    int sum = 0;\n    for (int m = n; m > 1; ) {\n        int t = tc.totient(m);\n        sum += t;\n        m = t;\n    }\n    return sum == n;\n}\n\nint main() {\n    totient_calculator tc(10000);\n    int count = 0, n = 1;\n    std::cout << \"First 20 perfect totient numbers:\\n\";\n    for (; count < 20; ++n) {\n        if (perfect_totient_number(tc, n))  {\n            if (count > 0)\n                std::cout << ' ';\n            ++count;\n            std::cout << n;\n        }\n    }\n    std::cout << '\\n';\n    return 0;\n}\n"}
{"id": 43880, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "C++": "#include <tr1/memory>\n#include <string>\n#include <iostream>\n#include <tr1/functional>\n\nusing namespace std;\nusing namespace std::tr1;\nusing std::tr1::function;\n\n\nclass IDelegate\n{\npublic:\n    virtual ~IDelegate() {}\n};\n\n\nclass IThing\n{\npublic:\n    virtual ~IThing() {}\n    virtual std::string Thing() = 0;\n};\n\n\nclass DelegateA : virtual public IDelegate\n{\n};\n \n\nclass DelegateB : public IThing, public IDelegate\n{\n    std::string Thing()\n    {\n        return \"delegate implementation\";\n    }\n};\n \nclass Delegator\n{\npublic:\n    std::string Operation()\n    {\n        if(Delegate) \n           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))\n            \n            return pThing->Thing();\n        \n        return \"default implementation\";\n    }\n \n    shared_ptr<IDelegate> Delegate;\n};\n \nint main()\n{\n    shared_ptr<DelegateA> delegateA(new DelegateA());\n    shared_ptr<DelegateB> delegateB(new DelegateB());\n    Delegator delegator;\n \n    \n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateA;\n    std::cout << delegator.Operation() << std::endl;\n \n    \n    delegator.Delegate = delegateB;\n    std::cout << delegator.Operation() << std::endl;\n\n\n}\n"}
{"id": 43881, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43882, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43883, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1)\n        total += power;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p)\n            sum += power;\n        total *= sum;\n    }\n    \n    if (n > 1)\n        total *= n + 1;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"Sum of divisors for the first \" << limit << \" positive integers:\\n\";\n    for (unsigned int n = 1; n <= limit; ++n) {\n        std::cout << std::setw(4) << divisor_sum(n);\n        if (n % 10 == 0)\n            std::cout << '\\n';\n    }\n}\n"}
{"id": 43884, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43885, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43886, "name": "Enforced immutability", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n", "C++": "#include <iostream>\n\nclass MyOtherClass\n{\npublic:\n  const int m_x;\n  MyOtherClass(const int initX = 0) : m_x(initX) { }\n\n};\n\nint main()\n{\n  MyOtherClass mocA, mocB(7);\n\n  std::cout << mocA.m_x << std::endl; \n  std::cout << mocB.m_x << std::endl; \n\n  \n  \n\n  return 0;\n}\n"}
{"id": 43887, "name": "Sutherland-Hodgman polygon clipping", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n", "C++": "#include <iostream>\n#include <span>\n#include <vector>\n\nstruct vec2 {\n    float x = 0.0f, y = 0.0f;\n\n    constexpr vec2 operator+(vec2 other) const {\n        return vec2{x + other.x, y + other.y};\n    }\n\n    constexpr vec2 operator-(vec2 other) const {\n        return vec2{x - other.x, y - other.y};\n    }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n    return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n           (1.0f / cross(a1 - a2, b1 - b2));\n}\n\n\nstd::vector<vec2> suther_land_hodgman(\n    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {\n    if (clip_polygon.empty() || subject_polygon.empty()) {\n        return {};\n    }\n\n    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};\n\n    vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n    std::vector<vec2> input;\n\n    for (vec2 p2 : clip_polygon) {\n        input.clear();\n        input.insert(input.end(), ring.begin(), ring.end());\n        vec2 s = input[input.size() - 1];\n\n        ring.clear();\n\n        for (vec2 e : input) {\n            if (is_inside(e, p1, p2)) {\n                if (!is_inside(s, p1, p2)) {\n                    ring.push_back(intersection(p1, p2, s, e));\n                }\n\n                ring.push_back(e);\n            } else if (is_inside(s, p1, p2)) {\n                ring.push_back(intersection(p1, p2, s, e));\n            }\n\n            s = e;\n        }\n\n        p1 = p2;\n    }\n\n    return ring;\n}\n\nint main(int argc, char **argv) {\n    \n    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},\n                              {350, 300}, {250, 300}, {200, 250},\n                              {150, 350}, {100, 250}, {100, 200}};\n\n    \n    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n    \n    std::vector<vec2> clipped_polygon =\n        suther_land_hodgman(subject_polygon, clip_polygon);\n\n    \n    std::cout << \"Clipped polygon points:\" << std::endl;\n    for (vec2 p : clipped_polygon) {\n        std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43888, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43889, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43890, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 43891, "name": "Spiral matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n"}
{"id": 43892, "name": "Spiral matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n"}
{"id": 43893, "name": "Optional parameters", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n"}
{"id": 43894, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 43895, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "C++": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n\nstruct Point {\n  int x, y;\n};\n\n\nclass MyBitmap {\n public:\n  MyBitmap() : pen_(nullptr) {}\n  ~MyBitmap() {\n    DeleteObject(pen_);\n    DeleteDC(hdc_);\n    DeleteObject(bmp_);\n  }\n\n  bool Create(int w, int h) {\n    BITMAPINFO\tbi;\n    ZeroMemory(&bi, sizeof(bi));\n\n    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n    bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    bi.bmiHeader.biCompression = BI_RGB;\n    bi.bmiHeader.biPlanes = 1;\n    bi.bmiHeader.biWidth = w;\n    bi.bmiHeader.biHeight = -h;\n\n    void *bits_ptr = nullptr;\n    HDC dc = GetDC(GetConsoleWindow());\n    bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n    if (!bmp_) return false;\n\n    hdc_ = CreateCompatibleDC(dc);\n    SelectObject(hdc_, bmp_);\n    ReleaseDC(GetConsoleWindow(), dc);\n\n    width_ = w;\n    height_ = h;\n\n    return true;\n  }\n\n  void SetPenColor(DWORD clr) {\n    if (pen_) DeleteObject(pen_);\n    pen_ = CreatePen(PS_SOLID, 1, clr);\n    SelectObject(hdc_, pen_);\n  }\n\n  bool SaveBitmap(const char* path) {\n    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n    if (file == INVALID_HANDLE_VALUE) {\n      return false;\n    }\n\n    BITMAPFILEHEADER fileheader;\n    BITMAPINFO infoheader;\n    BITMAP bitmap;    \n    GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n    DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n    ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n    ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n    ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n    infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n    infoheader.bmiHeader.biCompression = BI_RGB;\n    infoheader.bmiHeader.biPlanes = 1;\n    infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n    infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n    infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n    infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n    fileheader.bfType = 0x4D42;\n    fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n    fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n    GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n    DWORD wb;\n    WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n    WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n    WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n    CloseHandle(file);\n\n    delete[] dwp_bits;\n    return true;\n  }\n\n  HDC hdc() { return hdc_; }\n  int width() { return width_; }\n  int height() { return height_; }\n\n private:\n  HBITMAP bmp_;\n  HDC hdc_;\n  HPEN pen_;\n  int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n  int xd = x - point.x;\n  int yd = y - point.y;\n  return (xd * xd) + (yd * yd);\n}\n\n\nclass Voronoi {\n public:\n  void Make(MyBitmap* bmp, int count) {\n    bmp_ = bmp;\n    CreatePoints(count);\n    CreateColors();\n    CreateSites();\n    SetSitesPoints();\n  }\n\n private:\n  void CreateSites() {\n    int w = bmp_->width(), h = bmp_->height(), d;\n    for (int hh = 0; hh < h; hh++) {\n      for (int ww = 0; ww < w; ww++) {\n        int ind = -1, dist = INT_MAX;\n        for (size_t it = 0; it < points_.size(); it++) {\n          const Point& p = points_[it];\n          d = DistanceSqrd(p, ww, hh);\n          if (d < dist) {\n            dist = d;\n            ind = it;\n          }\n        }\n\n        if (ind > -1)\n          SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n        else\n          __asm nop \n        }\n    }\n  }\n\n  void SetSitesPoints() {\n    for (const auto& point : points_) {\n      int x = point.x, y = point.y;\n      for (int i = -1; i < 2; i++)\n        for (int j = -1; j < 2; j++)\n          SetPixel(bmp_->hdc(), x + i, y + j, 0);\n    }\n  }\n\n  void CreatePoints(int count) {\n    const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n    for (int i = 0; i < count; i++) {\n      points_.push_back({ rand() % w + 10, rand() % h + 10 });\n    }\n  }\n\n  void CreateColors() {\n    for (size_t i = 0; i < points_.size(); i++) {\n      DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n      colors_.push_back(c);\n    }\n  }\n\n  vector<Point> points_;\n  vector<DWORD> colors_;\n  MyBitmap* bmp_;\n};\n\n\nint main(int argc, char* argv[]) {\n  ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n  srand(GetTickCount());\n\n  MyBitmap bmp;\n  bmp.Create(512, 512);\n  bmp.SetPenColor(0);\n\n  Voronoi v;\n  v.Make(&bmp, 50);\n\n  BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n  bmp.SaveBitmap(\"v.bmp\");\n\n  system(\"pause\");\n\n  return 0;\n}\n"}
{"id": 43896, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n"}
{"id": 43897, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 43898, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "C++": "#include <iostream>\n#include <functional>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\ntemplate <typename T>\nstd::function<std::vector<T>(T)> s_of_n_creator(int n) {\n  std::vector<T> sample;\n  int i = 0;\n  return [=](T item) mutable {\n    i++;\n    if (i <= n) {\n      sample.push_back(item);\n    } else if (std::rand() % i < n) {\n      sample[std::rand() % n] = item;\n    }\n    return sample;\n  };\n}\n\nint main() {\n  std::srand(std::time(NULL));\n  int bin[10] = {0};\n  for (int trial = 0; trial < 100000; trial++) {\n    auto s_of_n = s_of_n_creator<int>(3);\n    std::vector<int> sample;\n    for (int i = 0; i < 10; i++)\n      sample = s_of_n(i);\n    for (int s : sample)\n      bin[s]++;\n  }\n  for (int x : bin)\n    std::cout << x << std::endl;\n  return 0;\n}\n"}
{"id": 43899, "name": "Faulhaber's triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n"}
{"id": 43900, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 43901, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 43902, "name": "Word wheel", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43903, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"}
{"id": 43904, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 43905, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 43906, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 43907, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 43908, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 43909, "name": "Primes - allocate descendants to their ancestors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n"}
{"id": 43910, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 43911, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 43912, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n"}
{"id": 43913, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "C++": "#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <cmath>\n \nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::function;\nusing std::transform;\nusing std::back_inserter;\n\ntypedef function<double(double)> FunType;\n\nvector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };\nvector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };\n\ntemplate <typename A, typename B, typename C>\nfunction<C(A)> compose(function<C(B)> f, function<B(A)> g) {\n    return [f,g](A x) { return f(g(x)); };\n}\n\nint main() {\n    vector<FunType> composedFuns;\n    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};\n\n    transform(B.begin(), B.end(),\n                A.begin(),\n                back_inserter(composedFuns),\n                compose<double, double, double>);\n\n    for (auto num: exNums)\n        for (auto fun: composedFuns)\n            cout << u8\"f\\u207B\\u00B9.f(\" << num << \") = \" << fun(num) << endl;\n\n    return 0;\n}\n"}
{"id": 43914, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n"}
{"id": 43915, "name": "XML_Output", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 43916, "name": "XML_Output", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 43917, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 43918, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 43919, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n"}
{"id": 43920, "name": "Guess the number_With feedback (player)", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <iterator>\n \nstruct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {\n  int i;\n  GuessNumberIterator() { }\n  GuessNumberIterator(int _i) : i(_i) { }\n  GuessNumberIterator& operator++() { ++i; return *this; }\n  GuessNumberIterator operator++(int) {\n    GuessNumberIterator tmp = *this; ++(*this); return tmp; }\n  bool operator==(const GuessNumberIterator& y) { return i == y.i; }\n  bool operator!=(const GuessNumberIterator& y) { return i != y.i; }\n  int operator*() {\n    std::cout << \"Is your number less than or equal to \" << i << \"? \";\n    std::string s;\n    std::cin >> s;\n    return (s != \"\" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;\n  }\n  GuessNumberIterator& operator--() { --i; return *this; }\n  GuessNumberIterator operator--(int) {\n    GuessNumberIterator tmp = *this; --(*this); return tmp; }\n  GuessNumberIterator& operator+=(int n) { i += n; return *this; }\n  GuessNumberIterator& operator-=(int n) { i -= n; return *this; }\n  GuessNumberIterator operator+(int n) {\n    GuessNumberIterator tmp = *this; return tmp += n; }\n  GuessNumberIterator operator-(int n) {\n    GuessNumberIterator tmp = *this; return tmp -= n; }\n  int operator-(const GuessNumberIterator &y) { return i - y.i; }\n  int operator[](int n) { return *(*this + n); }\n  bool operator<(const GuessNumberIterator &y) { return i < y.i; }\n  bool operator>(const GuessNumberIterator &y) { return i > y.i; }\n  bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }\n  bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }\n};\ninline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }\n \nconst int lower = 0;\nconst int upper = 100;\n \nint main() {\n  std::cout << \"Instructions:\\n\"\n\t    << \"Think of integer number from \" << lower << \" (inclusive) to \"\n\t    << upper << \" (exclusive) and\\n\"\n\t    << \"I will guess it. After each guess, I will ask you if it is less than\\n\"\n\t    << \"or equal to some number, and you will respond with \\\"yes\\\" or \\\"no\\\".\\n\";\n  int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;\n  std::cout << \"Your number is \" << answer << \".\\n\";\n  return 0;\n}\n"}
{"id": 43921, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n"}
{"id": 43922, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 43923, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nstd::vector<int> bins(const std::vector<int>& limits,\n                      const std::vector<int>& data) {\n    std::vector<int> result(limits.size() + 1, 0);\n    for (int n : data) {\n        auto i = std::upper_bound(limits.begin(), limits.end(), n);\n        ++result[i - limits.begin()];\n    }\n    return result;\n}\n\nvoid print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {\n    size_t n = limits.size();\n    if (n == 0)\n        return;\n    assert(n + 1 == bins.size());\n    std::cout << \"           < \" << std::setw(3) << limits[0] << \": \"\n              << std::setw(2) << bins[0] << '\\n';\n    for (size_t i = 1; i < n; ++i)\n        std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n                  << std::setw(3) << limits[i] << \": \" << std::setw(2)\n                  << bins[i] << '\\n';\n    std::cout << \">= \" << std::setw(3) << limits[n - 1] << \"          : \"\n              << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};\n    const std::vector<int> data1{\n        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    std::cout << \"Example 1:\\n\";\n    print_bins(limits1, bins(limits1, data1));\n\n    const std::vector<int> limits2{14,  18,  249, 312, 389,\n                                   392, 513, 591, 634, 720};\n    const std::vector<int> data2{\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    std::cout << \"\\nExample 2:\\n\";\n    print_bins(limits2, bins(limits2, data2));\n}\n"}
{"id": 43924, "name": "Fractal tree", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n", "C++": "#include <windows.h>\n#include <string>\n#include <math.h>\n\n\nusing namespace std;\n\n\nconst float PI = 3.1415926536f;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t   = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t   = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t   = 1;\n\tbi.bmiHeader.biWidth\t   =  w;\n\tbi.bmiHeader.biHeight\t   = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n    }\n\n    void setPenColor( DWORD clr )\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC()     { return hdc; }\n    int getWidth()  { return width; }\n    int getHeight() { return height; }\n\nprivate:\n    HBITMAP bmp;\n    HDC\t    hdc;\n    HPEN    pen;\n    int     width, height;\n};\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( int a, int b ) { x = a; y = b; }\n    void set( int a, int b ) { x = a; y = b; }\n    void rotate( float angle_r )\n    {\n\tfloat _x = static_cast<float>( x ),\n\t      _y = static_cast<float>( y ),\n\t       s = sinf( angle_r ), \n\t       c = cosf( angle_r ),\n\t       a = _x * c - _y * s, \n\t       b = _x * s + _y * c;\n\n\tx = static_cast<int>( a ); \n\ty = static_cast<int>( b );\n    }\n\n    int x, y;\n};\n\nclass fractalTree\n{\npublic:\n    fractalTree()\t\t      { _ang = DegToRadian( 24.0f ); }\n    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n    void create( myBitmap* bmp )\n    {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast<int>( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n    }\n\nprivate:\n    void drawRL( vector2* sp, float line_len, float a, bool rg )\n    {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast<int>( line_len ) );\n\n        if( rg ) a -= _ang;\n        else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n    }\n\n    myBitmap* _bmp;\n    float     _ang;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n    myBitmap bmp;\n    bmp.create( 640, 512 );\n    bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n    fractalTree tree;\n    tree.create( &bmp );\n\t\n    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n    bmp.saveBitmap( \"f:\n\t\n    system( \"pause\" );\n\t\n    return 0;\n}\n\n"}
{"id": 43925, "name": "Colour pinstripe_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n"}
{"id": 43926, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 43927, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "C++": "#include <iostream>\n#include <cstdint>\n\nstruct Date {\n    std::uint16_t year;\n    std::uint8_t month;\n    std::uint8_t day;\n};\n\nconstexpr bool leap(int year)  {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n    static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    \n    static const std::string days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n        \"Friday\", \"Saturday\"\n    };\n    \n    unsigned const c = date.year/100, r = date.year%100;\n    unsigned const s = r/12, t = r%12;\n    \n    unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n    unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const std::string months[] = {\"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    for (const Date& d : dates) {\n        std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n        std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n        std::cout << \"on a \" << weekday(d) << std::endl;\n    }\n    \n    return 0;\n}\n"}
{"id": 43928, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n"}
{"id": 43929, "name": "Animate a pendulum", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n"}
{"id": 43930, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 43931, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 43932, "name": "Create a file on magnetic tape", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n"}
{"id": 43933, "name": "Create a file on magnetic tape", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n", "C++": "#include <iostream>\n#include <fstream>\n\n#if defined(_WIN32) || defined(WIN32)\nconstexpr auto FILENAME = \"tape.file\";\n#else\nconstexpr auto FILENAME = \"/dev/tape\";\n#endif\n\nint main() {\n    std::filebuf fb;\n    fb.open(FILENAME,std::ios::out);\n    std::ostream os(&fb);\n    os << \"Hello World\\n\";\n    fb.close();\n    return 0;\n}\n"}
{"id": 43934, "name": "Sorting algorithms_Heapsort", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n", "C++": "#include <algorithm>\n#include <iterator>\n#include <iostream>\n\ntemplate<typename RandomAccessIterator>\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  std::make_heap(begin, end);\n  std::sort_heap(begin, end);\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  heap_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 43935, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 43936, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 43937, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n"}
{"id": 43938, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 43939, "name": "Merge and aggregate datasets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n", "C++": "#include <iostream>\n#include <optional>\n#include <ranges>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstruct Patient\n{\n    string ID;\n    string LastName;\n};\n\nstruct Visit\n{\n    string PatientID;\n    string Date;\n    optional<float> Score;\n};\n\nint main(void) \n{\n    auto patients = vector<Patient> {\n        {\"1001\", \"Hopper\"},\n        {\"4004\", \"Wirth\"},\n        {\"3003\", \"Kemeny\"},\n        {\"2002\", \"Gosling\"},\n        {\"5005\", \"Kurtz\"}};\n\n    auto visits = vector<Visit> {    \n        {\"2002\", \"2020-09-10\", 6.8},\n        {\"1001\", \"2020-09-17\", 5.5},\n        {\"4004\", \"2020-09-24\", 8.4},\n        {\"2002\", \"2020-10-08\", },\n        {\"1001\", \"\"          , 6.6},\n        {\"3003\", \"2020-11-12\", },\n        {\"4004\", \"2020-11-05\", 7.0},\n        {\"1001\", \"2020-11-19\", 5.3}};\n\n    \n    sort(patients.begin(), patients.end(), \n         [](const auto& a, const auto&b){ return a.ID < b.ID;});    \n\n    cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n    for(const auto& patient : patients)\n    {\n        \n        string lastVisit;\n        float sum = 0;\n        int numScores = 0;\n        \n        \n        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n        for(const auto& visit : visits | views::filter( patientFilter ))\n        {\n            if(visit.Score)\n            {\n                sum += *visit.Score;\n                numScores++;\n            }\n            lastVisit = max(lastVisit, visit.Date);\n        }\n        \n        \n        cout << \"|       \" << patient.ID << \" | \";\n        cout.width(8); cout << patient.LastName << \" | \";\n        cout.width(10); cout << lastVisit << \" | \";\n        if(numScores > 0)\n        {\n            cout.width(9); cout << sum << \" | \";\n            cout.width(9); cout << (sum / float(numScores));\n        }\n        else cout << \"          |          \";\n        cout << \" |\\n\";\n    }\n}\n"}
{"id": 43940, "name": "Euler method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n"}
{"id": 43941, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 43942, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 43943, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 43944, "name": "JortSort", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n"}
{"id": 43945, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n"}
{"id": 43946, "name": "Combinations and permutations", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n"}
{"id": 43947, "name": "Combinations and permutations", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n"}
{"id": 43948, "name": "Sort numbers lexicographically", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n"}
{"id": 43949, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n"}
{"id": 43950, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <string>\n#include <list>\n\nusing namespace std;\n\nbool cmp(const string& a, const string& b)\n{\n    return b.length() < a.length(); \n}\n\nvoid compareAndReportStringsLength(list<string> listOfStrings)\n{\n    if (!listOfStrings.empty())\n    {\n        char Q = '\"';\n        string has_length(\" has length \");\n        string predicate_max(\" and is the longest string\");\n        string predicate_min(\" and is the shortest string\");\n        string predicate_ave(\" and is neither the longest nor the shortest string\");\n\n        list<string> ls(listOfStrings); \n        ls.sort(cmp);\n        int max = ls.front().length();\n        int min = ls.back().length();\n\n        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)\n        {\n            int length = s->length();\n            string* predicate;\n            if (length == max)\n                predicate = &predicate_max;\n            else if (length == min)\n                predicate = &predicate_min;\n            else\n                predicate = &predicate_ave;\n\n            cout << Q << *s << Q << has_length << length << *predicate << endl;\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    list<string> listOfStrings{ \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n    compareAndReportStringsLength(listOfStrings);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43951, "name": "Sorting algorithms_Shell sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n"}
{"id": 43952, "name": "Doubly-linked list_Definition", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n"}
{"id": 43953, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n"}
{"id": 43954, "name": "Permutation test", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n", "C++": "#include<iostream>\n#include<vector>\n#include<numeric>\n#include<functional>\n\nclass\n{\npublic:\n    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}\nprivate:\n    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }\n    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}\n}combinations;\n\nint main()\n{\n    static constexpr int treatment = 9;\n    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,\n                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\n    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);\n\n    std::function<int (int, int, int)> pick;\n    pick = [&](int n, int from, int accumulated)\n            {\n                if(n == 0)\n                    return accumulated > treated ? 1 : 0;\n                else\n                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +\n                            (from > n ? pick(n, from - 1, accumulated) : 0);\n            };\n\n    int total   = combinations(data.size(), treatment);\n    int greater = pick(treatment, data.size(), 0);\n    int lesser  = total - greater;\n\n    std::cout << \"<= : \" << 100.0 * lesser  / total << \"%  \" << lesser  << std::endl\n              << \" > : \" << 100.0 * greater / total << \"%  \" << greater << std::endl;\n}\n"}
{"id": 43955, "name": "Möbius function", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <vector>\n\nconstexpr int MU_MAX = 1'000'000;\nstd::vector<int> MU;\n\nint mobiusFunction(int n) {\n    if (!MU.empty()) {\n        return MU[n];\n    }\n\n    \n    MU.resize(MU_MAX + 1, 1);\n    int root = sqrt(MU_MAX);\n\n    for (int i = 2; i <= root; i++) {\n        if (MU[i] == 1) {\n            \n            for (int j = i; j <= MU_MAX; j += i) {\n                MU[j] *= -i;\n            }\n            \n            for (int j = i * i; j <= MU_MAX; j += i * i) {\n                MU[j] = 0;\n            }\n        }\n    }\n\n    for (int i = 2; i <= MU_MAX; i++) {\n        if (MU[i] == i) {\n            MU[i] = 1;\n        } else if (MU[i] == -i) {\n            MU[i] = -1;\n        } else if (MU[i] < 0) {\n            MU[i] = 1;\n        } else if (MU[i] > 0) {\n            MU[i] = -1;\n        }\n    }\n\n    return MU[n];\n}\n\nint main() {\n    std::cout << \"First 199 terms of the möbius function are as follows:\\n    \";\n    for (int n = 1; n < 200; n++) {\n        std::cout << std::setw(2) << mobiusFunction(n) << \"  \";\n        if ((n + 1) % 20 == 0) {\n            std::cout << '\\n';\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 43956, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n"}
{"id": 43957, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 43958, "name": "Sorting algorithms_Permutation sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n", "C++": "#include <algorithm>\n\ntemplate<typename ForwardIterator>\n void permutation_sort(ForwardIterator begin, ForwardIterator end)\n{\n  while (std::next_permutation(begin, end))\n  {\n    \n  }\n}\n"}
{"id": 43959, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n"}
{"id": 43960, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43961, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43962, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 43963, "name": "Entropy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\ndouble log2( double number ) {\n   return log( number ) / log( 2 ) ;\n}\n\nint main( int argc , char *argv[ ] ) {\n   std::string teststring( argv[ 1 ] ) ;\n   std::map<char , int> frequencies ;\n   for ( char c : teststring )\n     frequencies[ c ] ++ ;\n   int numlen = teststring.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent -= freq * log2( freq ) ;\n   }\n  \n   std::cout << \"The information content of \" << teststring \n      << \" is \" << infocontent << std::endl ;\n   return 0 ;\n}\n"}
{"id": 43964, "name": "Tokenize a string with escaping", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n"}
{"id": 43965, "name": "Hello world_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n"}
{"id": 43966, "name": "Sexy primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n", "C++": "#include <array>\n#include <iostream>\n#include <vector>\n#include <boost/circular_buffer.hpp>\n#include \"prime_sieve.hpp\"\n\nint main() {\n    using std::cout;\n    using std::vector;\n    using boost::circular_buffer;\n    using group_buffer = circular_buffer<vector<int>>;\n\n    const int max = 1000035;\n    const int max_group_size = 5;\n    const int diff = 6;\n    const int array_size = max + diff;\n    const int max_groups = 5;\n    const int max_unsexy = 10;\n\n    \n    prime_sieve sieve(array_size);\n\n    std::array<int, max_group_size> group_count{0};\n    vector<group_buffer> groups(max_group_size, group_buffer(max_groups));\n    int unsexy_count = 0;\n    circular_buffer<int> unsexy_primes(max_unsexy);\n    vector<int> group;\n\n    for (int p = 2; p < max; ++p) {\n        if (!sieve.is_prime(p))\n            continue;\n        if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {\n            \n            ++unsexy_count;\n            unsexy_primes.push_back(p);\n        } else {\n            \n            group.clear();\n            group.push_back(p);\n            for (int group_size = 1; group_size < max_group_size; group_size++) {\n                int next_p = p + group_size * diff;\n                if (next_p >= max || !sieve.is_prime(next_p))\n                    break;\n                group.push_back(next_p);\n                ++group_count[group_size];\n                groups[group_size].push_back(group);\n            }\n        }\n    }\n\n    for (int size = 1; size < max_group_size; ++size) {\n        cout << \"number of groups of size \" << size + 1 << \" is \" << group_count[size] << '\\n';\n        cout << \"last \" << groups[size].size() << \" groups of size \" << size + 1 << \":\";\n        for (const vector<int>& group : groups[size]) {\n            cout << \" (\";\n            for (size_t i = 0; i < group.size(); ++i) {\n                if (i > 0)\n                    cout << ' ';\n                cout << group[i];\n            }\n            cout << \")\";\n        }\n        cout << \"\\n\\n\";\n    }\n    cout << \"number of unsexy primes is \" << unsexy_count << '\\n';\n    cout << \"last \" << unsexy_primes.size() << \" unsexy primes:\";\n    for (int prime : unsexy_primes)\n        cout << ' ' << prime;\n    cout << '\\n';\n    return 0;\n}\n"}
{"id": 43967, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 43968, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n"}
{"id": 43969, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n"}
{"id": 43970, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n"}
{"id": 43971, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n"}
{"id": 43972, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n"}
{"id": 43973, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "C++": "#include <iostream>\n#include <forward_list>\n\nint main()\n{\n    std::forward_list<int> list{1, 2, 3, 4, 5};\n    for (int e : list)\n        std::cout << e << std::endl;\n}\n"}
{"id": 43974, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "C++": "#include <fstream>\n#include <cstdio>\n\nint main() {\n    constexpr auto dimx = 800u, dimy = 800u;\n\n    using namespace std;\n    ofstream ofs(\"first.ppm\", ios_base::out | ios_base::binary);\n    ofs << \"P6\" << endl << dimx << ' ' << dimy << endl << \"255\" << endl;\n\n    for (auto j = 0u; j < dimy; ++j)\n        for (auto i = 0u; i < dimx; ++i)\n            ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);       \n\n    ofs.close();\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43975, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n"}
{"id": 43976, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "C++": "#include <cstdio>\n#include <direct.h>\n\nint main() {\n\tremove( \"input.txt\" );\n\tremove( \"/input.txt\" );\n\t_rmdir( \"docs\" );\n\t_rmdir( \"/docs\" );\n\n\treturn 0;\n}\n"}
{"id": 43977, "name": "Discordian date", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <iterator>\nusing namespace std;\nclass myTuple\n{\npublic:\n    void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }\n    bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }\n    string second() { return t.second; }\nprivate:\n    pair<pair<int, int>, string> t;\n};\nclass discordian\n{\npublic:\n    discordian() {\n        myTuple t;\n        t.set( 5, 1, \"Mungday\" ); holyday.push_back( t ); t.set( 19, 2, \"Chaoflux\" ); holyday.push_back( t );\n        t.set( 29, 2, \"St. Tib's Day\" ); holyday.push_back( t ); t.set( 19, 3, \"Mojoday\" ); holyday.push_back( t );\n        t.set( 3, 5, \"Discoflux\" ); holyday.push_back( t ); t.set( 31, 5, \"Syaday\" ); holyday.push_back( t );\n        t.set( 15, 7, \"Confuflux\" ); holyday.push_back( t ); t.set( 12, 8, \"Zaraday\" ); holyday.push_back( t ); \n        t.set( 26, 9, \"Bureflux\" ); holyday.push_back( t ); t.set( 24, 10, \"Maladay\" ); holyday.push_back( t ); \n        t.set( 8, 12, \"Afflux\" ); holyday.push_back( t ); \n        seasons.push_back( \"Chaos\" ); seasons.push_back( \"Discord\" ); seasons.push_back( \"Confusion\" ); \n        seasons.push_back( \"Bureaucracy\" ); seasons.push_back( \"The Aftermath\" );\n        wdays.push_back( \"Setting Orange\" ); wdays.push_back( \"Sweetmorn\" ); wdays.push_back( \"Boomtime\" );\n        wdays.push_back( \"Pungenday\" ); wdays.push_back( \"Prickle-Prickle\" ); \n    }\n    void convert( int d, int m, int y ) {\n        if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { \n            cout << \"\\nThis is not a date!\"; \n            return; \n        }\n        vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); \n        int dd = d, day, wday, sea,  yr = y + 1166;\n        for( int x = 1; x < m; x++ )\n            dd += getMaxDay( x, 1 );\n        day = dd % 73; if( !day ) day = 73; \n        wday = dd % 5; \n        sea  = ( dd - 1 ) / 73;\n        if( d == 29 && m == 2 && isLeap( y ) ) { \n            cout << ( *f ).second() << \" \" << seasons[sea] << \", Year of Our Lady of Discord \" << yr; \n            return; \n        }\n        cout << wdays[wday] << \" \" << seasons[sea] << \" \" << day;\n        if( day > 10 && day < 14 ) cout << \"th\"; \n        else switch( day % 10) { \n            case 1: cout << \"st\"; break; \n            case 2: cout << \"nd\"; break; \n            case 3: cout << \"rd\"; break; \n            default: cout << \"th\"; \n        }\n        cout << \", Year of Our Lady of Discord \" << yr;\n        if( f != holyday.end() ) cout << \" - \" << ( *f ).second();\n    }\nprivate:\n    int getMaxDay( int m, int y ) { \n        int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; \n    }\n    bool isLeap( int y ) { \n        bool l = false; \n        if( !( y % 4 ) ) { \n            if( y % 100 ) l = true; \n            else if( !( y % 400 ) ) l = true; \n        }\n        return l; \n    }\n    vector<myTuple> holyday; vector<string> seasons, wdays;\n};\nint main( int argc, char* argv[] ) {\n    string date; discordian disc;\n    while( true ) {\n        cout << \"Enter a date (dd mm yyyy) or 0 to quit: \"; getline( cin, date ); if( date == \"0\" ) break;\n        if( date.length() == 10 ) {\n            istringstream iss( date ); \n            vector<string> vc;\n            copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );\n            disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); \n            cout << \"\\n\\n\\n\";\n        } else cout << \"\\nIs this a date?!\\n\\n\";\n    }\n    return 0;\n}\n"}
{"id": 43978, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"}
{"id": 43979, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "C++": "#include <time.h>\n#include <iostream>\n#include <string>\n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n    flip() { field = 0; target = 0; }\n    void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n    void gameLoop()\n    {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t    display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t    for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t    {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t    }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n    }\n\n    void display()\n    { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n    void output( string t, byte* f )\n    {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast<char>( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t    cout << static_cast<char>( y + 'a' ) << \" \";\n\t    for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast<char>( f[x + y * wid] + 48 ) << \" \";\n\t    cout << endl;\n\t}\n\tcout << endl << endl;\n    }\n\n    bool solved()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n    }\n\n    void createTarget()\n    {\n\tfor( int y = 0; y < hei; y++ )\n\t    for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t        else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n    }\n\n    void flipCol( int c )\n    { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n    void flipRow( int r )\n    { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n    void calcStartPos()\n    {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n    }\n\n    void createField()\n    {\n        if( field ){ delete [] field; delete [] target; }\n        int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n    }\n\n    float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }\n\n    byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"}
{"id": 43980, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n"}
{"id": 43981, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "C++": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n    \n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h << \n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n"}
{"id": 43982, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 43983, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "C++": "#include <random>\n#include <random>\n#include <vector>\n#include <iostream>\n\n#define MAX_N 20\n#define TIMES 1000000\n\n\nstatic std::random_device rd;  \nstatic std::mt19937 gen(rd()); \nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n    int r, rmax = RAND_MAX / n * n;\n    dis=std::uniform_int_distribution<int>(0,rmax) ;\n    r = dis(gen);\n    return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n    \n    static std::vector<unsigned long long>factorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n    long double sum = 0;\n    for (size_t i = 1; i <= n; i++)\n        sum += factorial(n) / pow(n, i) / factorial(n - i);\n    return sum;\n}\n\nint test(int n, int times) {\n    int i, count = 0;\n    for (i = 0; i < times; i++) {\n        unsigned int x = 1, bits = 0;\n        while (!(bits & x)) {\n            count++;\n            bits |= x;\n            x = static_cast<unsigned int>(1 << randint(n));\n        }\n    }\n    return count;\n}\n\nint main() {\n    puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n    int n;\n    for (n = 1; n <= MAX_N; n++) {\n        int cnt = test(n, TIMES);\n        long double avg = (double)cnt / TIMES;\n        long double theory = expected(static_cast<size_t>(n));\n        long double diff = (avg / theory - 1) * 100;\n        printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));\n    }\n    return 0;\n}\n"}
{"id": 43984, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n"}
{"id": 43985, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string original( \"Mary had a X lamb.\" ) , toBeReplaced( \"X\" ) ,\n      replacement ( \"little\" ) ;\n   std::string newString = original.replace( original.find( \"X\" ) ,\n\t toBeReplaced.length( ) , replacement ) ;\n   std::cout << \"String after replacement: \" << newString << \" \\n\" ;\n   return 0 ;\n}\n"}
{"id": 43986, "name": "Sorting algorithms_Patience sort", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n", "C++": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <iterator>\n#include <algorithm>\n#include <cassert>\n\ntemplate <class E>\nstruct pile_less {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() < pile2.top();\n  }\n};\n\ntemplate <class E>\nstruct pile_greater {\n  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {\n    return pile1.top() > pile2.top();\n  }\n};\n\n\ntemplate <class Iterator>\nvoid patience_sort(Iterator first, Iterator last) {\n  typedef typename std::iterator_traits<Iterator>::value_type E;\n  typedef std::stack<E> Pile;\n\n  std::vector<Pile> piles;\n  \n  for (Iterator it = first; it != last; it++) {\n    E& x = *it;\n    Pile newPile;\n    newPile.push(x);\n    typename std::vector<Pile>::iterator i =\n      std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());\n    if (i != piles.end())\n      i->push(x);\n    else\n      piles.push_back(newPile);\n  }\n\n  \n  \n  std::make_heap(piles.begin(), piles.end(), pile_greater<E>());\n  for (Iterator it = first; it != last; it++) {\n    std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());\n    Pile &smallPile = piles.back();\n    *it = smallPile.top();\n    smallPile.pop();\n    if (smallPile.empty())\n      piles.pop_back();\n    else\n      std::push_heap(piles.begin(), piles.end(), pile_greater<E>());\n  }\n  assert(piles.empty());\n}\n\nint main() {\n  int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n  patience_sort(a, a+sizeof(a)/sizeof(*a));\n  std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  return 0;\n}\n"}
{"id": 43987, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n"}
{"id": 43988, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "C++": "#include <array>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n\nclass sequence_generator {\npublic:\n    sequence_generator();\n    std::string generate_sequence(size_t length);\n    void mutate_sequence(std::string&);\n    static void print_sequence(std::ostream&, const std::string&);\n    enum class operation { change, erase, insert };\n    void set_weight(operation, unsigned int);\nprivate:\n    char get_random_base() {\n        return bases_[base_dist_(engine_)];\n    }\n    operation get_random_operation();\n    static const std::array<char, 4> bases_;\n    std::mt19937 engine_;\n    std::uniform_int_distribution<size_t> base_dist_;\n    std::array<unsigned int, 3> operation_weight_;\n    unsigned int total_weight_;\n};\n\nconst std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n    base_dist_(0, bases_.size() - 1),\n    total_weight_(operation_weight_.size()) {\n    operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);\n    unsigned int n = op_dist(engine_), op = 0, weight = 0;\n    for (; op < operation_weight_.size(); ++op) {\n        weight += operation_weight_[op];\n        if (n < weight)\n            break;\n    }\n    return static_cast<operation>(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n    total_weight_ -= operation_weight_[static_cast<size_t>(op)];\n    operation_weight_[static_cast<size_t>(op)] = weight;\n    total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n    std::string sequence;\n    sequence.reserve(length);\n    for (size_t i = 0; i < length; ++i)\n        sequence += get_random_base();\n    return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);\n    size_t pos = dist(engine_);\n    char b;\n    switch (get_random_operation()) {\n    case operation::change:\n        b = get_random_base();\n        std::cout << \"Change base at position \" << pos << \" from \"\n            << sequence[pos] << \" to \" << b << '\\n';\n        sequence[pos] = b;\n        break;\n    case operation::erase:\n        std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n            << pos << '\\n';\n        sequence.erase(pos, 1);\n        break;\n    case operation::insert:\n        b = get_random_base();\n        std::cout << \"Insert base \" << b << \" at position \"\n            << pos << '\\n';\n        sequence.insert(pos, 1, b);\n        break;\n    }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n    constexpr size_t base_count = bases_.size();\n    std::array<size_t, base_count> count = { 0 };\n    for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n        if (i % 50 == 0) {\n            if (i != 0)\n                out << '\\n';\n            out << std::setw(3) << i << \": \";\n        }\n        out << sequence[i];\n        for (size_t j = 0; j < base_count; ++j) {\n            if (bases_[j] == sequence[i]) {\n                ++count[j];\n                break;\n            }\n        }\n    }\n    out << '\\n';\n    out << \"Base counts:\\n\";\n    size_t total = 0;\n    for (size_t j = 0; j < base_count; ++j) {\n        total += count[j];\n        out << bases_[j] << \": \" << count[j] << \", \";\n    }\n    out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n    sequence_generator gen;\n    gen.set_weight(sequence_generator::operation::change, 2);\n    std::string sequence = gen.generate_sequence(250);\n    std::cout << \"Initial sequence:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    constexpr int count = 10;\n    for (int i = 0; i < count; ++i)\n        gen.mutate_sequence(sequence);\n    std::cout << \"After \" << count << \" mutations:\\n\";\n    sequence_generator::print_sequence(std::cout, sequence);\n    return 0;\n}\n"}
{"id": 43989, "name": "Tau number", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n", "C++": "#include <iomanip>\n#include <iostream>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1)\n        ++total;\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p)\n            ++count;\n        total *= count;\n    }\n    \n    if (n > 1)\n        total *= 2;\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    std::cout << \"The first \" << limit << \" tau numbers are:\\n\";\n    unsigned int count = 0;\n    for (unsigned int n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            std::cout << std::setw(6) << n;\n            ++count;\n            if (count % 10 == 0)\n                std::cout << '\\n';\n        }\n    }\n}\n"}
{"id": 43990, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n"}
{"id": 43991, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "C++": "#include <iostream>\n#include <vector>\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n    auto it = v.cbegin();\n    auto end = v.cend();\n\n    os << '[';\n    if (it != end) {\n        os << *it;\n        it = std::next(it);\n    }\n    while (it != end) {\n        os << \", \" << *it;\n        it = std::next(it);\n    }\n    return os << ']';\n}\n\nusing Matrix = std::vector<std::vector<double>>;\n\nMatrix squareMatrix(size_t n) {\n    Matrix m;\n    for (size_t i = 0; i < n; i++) {\n        std::vector<double> inner;\n        for (size_t j = 0; j < n; j++) {\n            inner.push_back(nan(\"\"));\n        }\n        m.push_back(inner);\n    }\n    return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n    auto length = a.size() - 1;\n    auto result = squareMatrix(length);\n    for (int i = 0; i < length; i++) {\n        for (int j = 0; j < length; j++) {\n            if (i < x && j < y) {\n                result[i][j] = a[i][j];\n            } else if (i >= x && j < y) {\n                result[i][j] = a[i + 1][j];\n            } else if (i < x && j >= y) {\n                result[i][j] = a[i][j + 1];\n            } else {\n                result[i][j] = a[i + 1][j + 1];\n            }\n        }\n    }\n    return result;\n}\n\ndouble det(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    int sign = 1;\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += sign * a[0][i] * det(minor(a, 0, i));\n        sign *= -1;\n    }\n    return sum;\n}\n\ndouble perm(const Matrix &a) {\n    if (a.size() == 1) {\n        return a[0][0];\n    }\n\n    double sum = 0;\n    for (size_t i = 0; i < a.size(); i++) {\n        sum += a[0][i] * perm(minor(a, 0, i));\n    }\n    return sum;\n}\n\nvoid test(const Matrix &m) {\n    auto p = perm(m);\n    auto d = det(m);\n\n    std::cout << m << '\\n';\n    std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n    test({ {1, 2}, {3, 4} });\n    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });\n\n    return 0;\n}\n"}
{"id": 43992, "name": "Partition function P", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n"}
{"id": 43993, "name": "Partition function P", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n", "C++": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nusing big_int = mpz_class;\n\nbig_int partitions(int n) {\n    std::vector<big_int> p(n + 1);\n    p[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int k = 1;; ++k) {\n            int j = (k * (3*k - 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n            j = (k * (3*k + 1))/2;\n            if (j > i)\n                break;\n            if (k & 1)\n                p[i] += p[i - j];\n            else\n                p[i] -= p[i - j];\n        }\n    }\n    return p[n];\n}\n\nint main() {\n    auto start = std::chrono::steady_clock::now();\n    auto result = partitions(6666);\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double, std::milli> ms(end - start);\n    std::cout << result << '\\n';\n    std::cout << \"elapsed time: \" << ms.count() << \" milliseconds\\n\";\n}\n"}
{"id": 43994, "name": "Wireworld", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n", "C++": "#include <ggi/ggi.h>\n#include <set>\n#include <map>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <unistd.h> \n\nenum cell_type { none, wire, head, tail };\n\n\n\n\n\n\n\nclass display\n{\npublic:\n  display(int sizex, int sizey, int pixsizex, int pixsizey,\n          ggi_color* colors);\n  ~display()\n  {\n    ggiClose(visual);\n    ggiExit();\n  }\n\n  void flush();\n  bool keypressed() { return ggiKbhit(visual); }\n  void clear();\n  void putpixel(int x, int y, cell_type c);\nprivate:\n  ggi_visual_t visual;\n  int size_x, size_y;\n  int pixel_size_x, pixel_size_y;\n  ggi_pixel pixels[4];\n};\n\ndisplay::display(int sizex, int sizey, int pixsizex, int pixsizey,\n                 ggi_color* colors):\n  pixel_size_x(pixsizex),\n  pixel_size_y(pixsizey)\n{\n  if (ggiInit() < 0)\n  {\n    std::cerr << \"couldn't open ggi\\n\";\n    exit(1);\n  }\n\n  visual = ggiOpen(NULL);\n  if (!visual)\n  {\n    ggiPanic(\"couldn't open visual\\n\");\n  }\n\n  ggi_mode mode;\n  if (ggiCheckGraphMode(visual, sizex, sizey,\n                        GGI_AUTO, GGI_AUTO, GT_4BIT,\n                        &mode) != 0)\n  {\n    if (GT_DEPTH(mode.graphtype) < 2) \n      ggiPanic(\"low-color displays are not supported!\\n\");\n  }\n  if (ggiSetMode(visual, &mode) != 0)\n  {\n    ggiPanic(\"couldn't set graph mode\\n\");\n  }\n  ggiAddFlags(visual, GGIFLAG_ASYNC);\n\n  size_x = mode.virt.x;\n  size_y = mode.virt.y;\n\n  for (int i = 0; i < 4; ++i)\n    pixels[i] = ggiMapColor(visual, colors+i);\n}\n\nvoid display::flush()\n{\n  \n  ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));\n\n  \n  ggiFlush(visual);\n\n  \n  \n  \n  ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));\n}\n\nvoid display::clear()\n{\n  ggiSetGCForeground(visual, pixels[0]);\n  ggiDrawBox(visual, 0, 0, size_x, size_y);\n}\n\nvoid display::putpixel(int x, int y, cell_type cell)\n{\n  \n  \n  ggiSetGCForeground(visual, pixels[cell]);\n  ggiDrawBox(visual,\n             x*pixel_size_x, y*pixel_size_y,\n             pixel_size_x, pixel_size_y);\n}\n\n\n\n\n\n\nclass wireworld\n{\npublic:\n  void set(int posx, int posy, cell_type type);\n  void draw(display& destination);\n  void step();\nprivate:\n  typedef std::pair<int, int> position;\n  typedef std::set<position> position_set;\n  typedef position_set::iterator positer;\n  position_set wires, heads, tails;\n};\n\nvoid wireworld::set(int posx, int posy, cell_type type)\n{\n  position p(posx, posy);\n  wires.erase(p);\n  heads.erase(p);\n  tails.erase(p);\n  switch(type)\n  {\n  case head:\n    heads.insert(p);\n    break;\n  case tail:\n    tails.insert(p);\n    break;\n  case wire:\n    wires.insert(p);\n    break;\n  }\n}\n\nvoid wireworld::draw(display& destination)\n{\n  destination.clear();\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    destination.putpixel(i->first, i->second, head);\n  for (positer i = tails.begin(); i != tails.end(); ++i)\n    destination.putpixel(i->first, i->second, tail);\n  for (positer i = wires.begin(); i != wires.end(); ++i)\n    destination.putpixel(i->first, i->second, wire);\n  destination.flush();\n}\n\nvoid wireworld::step()\n{\n  std::map<position, int> new_heads;\n  for (positer i = heads.begin(); i != heads.end(); ++i)\n    for (int dx = -1; dx <= 1; ++dx)\n      for (int dy = -1; dy <= 1; ++dy)\n      {\n        position pos(i->first + dx, i->second + dy);\n        if (wires.count(pos))\n          new_heads[pos]++;\n      }\n  wires.insert(tails.begin(), tails.end());\n  tails.swap(heads);\n  heads.clear();\n  for (std::map<position, int>::iterator i = new_heads.begin();\n       i != new_heads.end();\n       ++i)\n  {\n\n    if (i->second < 3)\n    {\n      wires.erase(i->first);\n      heads.insert(i->first);\n    }\n  }\n}\n\nggi_color colors[4] =\n  {{ 0x0000, 0x0000, 0x0000 },  \n   { 0x8000, 0x8000, 0x8000 },  \n   { 0xffff, 0xffff, 0x0000 },  \n   { 0xffff, 0x0000, 0x0000 }}; \n\nint main(int argc, char* argv[])\n{\n  int display_x = 800;\n  int display_y = 600;\n  int pixel_x = 5;\n  int pixel_y = 5;\n\n  if (argc < 2)\n  {\n    std::cerr << \"No file name given!\\n\";\n    return 1;\n  }\n\n  \n  std::ifstream f(argv[1]);\n  wireworld w;\n  std::string line;\n  int line_number = 0;\n  while (std::getline(f, line))\n  {\n    for (int col = 0; col < line.size(); ++col)\n    {\n      switch (line[col])\n      {\n      case 'h': case 'H':\n        w.set(col, line_number, head);\n        break;\n      case 't': case 'T':\n        w.set(col, line_number, tail);\n        break;\n      case 'w': case 'W': case '.':\n        w.set(col, line_number, wire);\n        break;\n      default:\n        std::cerr << \"unrecognized character: \" << line[col] << \"\\n\";\n        return 1;\n      case ' ':\n        ; \n      }\n    }\n    ++line_number;\n  }\n\n  display d(display_x, display_y, pixel_x, pixel_y, colors);\n\n  w.draw(d);\n\n  while (!d.keypressed())\n  {\n    usleep(100000);\n    w.step();\n    w.draw(d);\n  }\n  std::cout << std::endl;\n}\n"}
{"id": 43995, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "C++": "#include <algorithm>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nconst double epsilon = numeric_limits<float>().epsilon();\nconst numeric_limits<double> DOUBLE;\nconst double MIN = DOUBLE.min();\nconst double MAX = DOUBLE.max();\n\nstruct Point { const double x, y; };\n\nstruct Edge {\n    const Point a, b;\n\n    bool operator()(const Point& p) const\n    {\n        if (a.y > b.y) return Edge{ b, a }(p);\n        if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });\n        if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;\n        if (p.x < min(a.x, b.x)) return true;\n        auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;\n        auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;\n        return blue >= red;\n    }\n};\n\nstruct Figure {\n    const string  name;\n    const initializer_list<Edge> edges;\n\n    bool contains(const Point& p) const\n    {\n        auto c = 0;\n        for (auto e : edges) if (e(p)) c++;\n        return c % 2 != 0;\n    }\n\n    template<unsigned char W = 3>\n    void check(const initializer_list<Point>& points, ostream& os) const\n    {\n        os << \"Is point inside figure \" << name <<  '?' << endl;\n        for (auto p : points)\n            os << \"  (\" << setw(W) << p.x << ',' << setw(W) << p.y << \"): \" << boolalpha << contains(p) << endl;\n        os << endl;\n    }\n};\n\nint main()\n{\n    const initializer_list<Point> points =  { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };\n    const Figure square = { \"Square\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }\n    };\n\n    const Figure square_hole = { \"Square hole\",\n        {  {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},\n           {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure strange = { \"Strange\",\n        {  {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},\n           {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}\n        }\n    };\n\n    const Figure exagon = { \"Exagon\",\n        {  {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},\n           {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}\n        }\n    };\n\n    for(auto f : {square, square_hole, strange, exagon})\n        f.check(points, cout);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 43996, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n"}
{"id": 43997, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "C++": "#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n\n\nclass EllipticPoint\n{\n    double m_x, m_y;\n    static constexpr double ZeroThreshold = 1e20;\n    static constexpr double B = 7; \n                                  \n    \n    void Double() noexcept\n    {\n        if(IsZero())\n        {\n            \n            return;\n        }\n        \n        \n        \n        if(m_y == 0)\n        {\n            \n            \n            *this = EllipticPoint();\n        }\n        else\n        {\n            double L = (3 * m_x * m_x) / (2 * m_y);\n            double newX = L * L -  2 * m_x;\n            m_y = L * (m_x - newX) - m_y;\n            m_x = newX;\n        }\n    }\n    \npublic:\n    friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n    \n    constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n    \n    \n    explicit EllipticPoint(double yCoordinate) noexcept\n    {\n        m_y = yCoordinate;\n        m_x = cbrt(m_y * m_y - B);\n    }\n\n    \n    bool IsZero() const noexcept\n    {\n        \n        bool isNotZero =  abs(m_y) < ZeroThreshold;\n        return !isNotZero;\n    }\n\n    \n    EllipticPoint operator-() const noexcept\n    {\n        EllipticPoint negPt;\n        negPt.m_x = m_x;\n        negPt.m_y = -m_y;\n        \n        return negPt;\n    }\n\n    \n    EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n    {\n        if(IsZero())\n        {\n            *this = rhs;\n        }\n        else if (rhs.IsZero())\n        {\n            \n            \n        }\n        else\n        {\n            double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n            if(isfinite(L))\n            {\n                double newX = L * L - m_x - rhs.m_x;\n                m_y = L * (m_x - newX) - m_y;\n                m_x = newX;\n            }\n            else\n            {\n                if(signbit(m_y) != signbit(rhs.m_y))\n                {\n                    \n                    *this = EllipticPoint();\n                }\n                else\n                {\n                    \n                    Double();\n                }\n            }\n        }\n\n        return *this;\n    }\n\n    \n    EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n    {\n        *this+= -rhs;\n        return *this;\n    }\n    \n    \n    EllipticPoint& operator*=(int rhs) noexcept\n    {\n        EllipticPoint r;\n        EllipticPoint p = *this;\n\n        if(rhs < 0)\n        {\n            \n            rhs = -rhs;\n            p = -p;\n        }\n        \n        for (int i = 1; i <= rhs; i <<= 1) \n        {\n            if (i & rhs) r += p;\n            p.Double();\n        }\n\n        *this = r;\n        return *this;\n    }\n};\n\n\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n    lhs += -rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n    lhs *= rhs;\n    return lhs;\n}\n\n\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n    rhs *= lhs;\n    return rhs;\n}\n\n\n\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n    if(pt.IsZero()) cout << \"(Zero)\\n\";\n    else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n    return os;\n}\n\nint main(void) {\n    const EllipticPoint a(1), b(2);\n    cout << \"a = \" << a;\n    cout << \"b = \" << b;\n    const EllipticPoint c = a + b;\n    cout << \"c = a + b = \"       << c;\n    cout << \"a + b - c = \"       << a + b - c;\n    cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n    cout << \"a + a + a + a + a - 5 * a = \"         << a + a + a + a + a - 5 * a;\n    cout << \"a * 12345 = \"                         << a * 12345;\n    cout << \"a * -12345 = \"                        << a * -12345;\n    cout << \"a * 12345 + a * -12345 = \"            << a * 12345 + a * -12345;\n    cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n    cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n    const EllipticPoint zero;\n    EllipticPoint g;\n    cout << \"g = zero = \"      << g;\n    cout << \"g += a = \"        << (g+=a);\n    cout << \"g += zero = \"     << (g+=zero);\n    cout << \"g += b = \"        << (g+=b);\n    cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n    EllipticPoint special(0);  \n    cout << \"special = \"      << special; \n    cout << \"special *= 2 = \" << (special*=2); \n    \n    return 0;\n}\n"}
{"id": 43998, "name": "Count occurrences of a substring", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n", "C++": "#include <iostream>\n#include <string>\n\n\nint countSubstring(const std::string& str, const std::string& sub)\n{\n    if (sub.length() == 0) return 0;\n    int count = 0;\n    for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n    {\n        ++count;\n    }\n    return count;\n}\n\nint main()\n{\n    std::cout << countSubstring(\"the three truths\", \"th\")    << '\\n';\n    std::cout << countSubstring(\"ababababab\", \"abab\")        << '\\n';\n    std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n    return 0;\n}\n"}
{"id": 43999, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n"}
{"id": 44000, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n"}
{"id": 44001, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "C++": "#include <cstdio>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() { \n  vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;\n  for (int x : lst) w.push_back({x, x});\n  while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());\n    for (int x : lst) if ((sum = get<1>(i) + x) == 13)\n        printf(\"%d%d \", get<0>(i), x);\n      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }\n  return 0; }\n"}
{"id": 44002, "name": "String comparison", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <string>\n\ntemplate <typename T>\nvoid demo_compare(const T &a, const T &b, const std::string &semantically) {\n    std::cout << a << \" and \" << b << \" are \" << ((a == b) ? \"\" : \"not \")\n              << \"exactly \" << semantically << \" equal.\" << std::endl;\n\n    std::cout << a << \" and \" << b << \" are \" << ((a != b) ? \"\" : \"not \")\n              << semantically << \"inequal.\" << std::endl;\n\n    std::cout << a << \" is \" << ((a < b) ? \"\" : \"not \") << semantically\n              << \" ordered before \" << b << '.' << std::endl;\n\n    std::cout << a << \" is \" << ((a > b) ? \"\" : \"not \") << semantically\n              << \" ordered after \" << b << '.' << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n    \n    std::string a((argc > 1) ? argv[1] : \"1.2.Foo\");\n    std::string b((argc > 2) ? argv[2] : \"1.3.Bar\");\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    std::transform(a.begin(), a.end(), a.begin(), ::tolower);\n    std::transform(b.begin(), b.end(), b.begin(), ::tolower);\n    demo_compare<std::string>(a, b, \"lexically\");\n\n    \n    \n    double numA, numB;\n    std::istringstream(a) >> numA;\n    std::istringstream(b) >> numB;\n    demo_compare<double>(numA, numB, \"numerically\");\n    return (a == b);\n}\n"}
{"id": 44003, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char **argv)\n{\n\tif(argc>1)\n\t{\n\t\tofstream Notes(note_file, ios::app);\n\t\ttime_t timer = time(NULL);\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\tNotes << asctime(localtime(&timer)) << '\\t';\n\t\t\tfor(int i=1;i<argc;i++)\n\t\t\t\tNotes << argv[i] << ' ';\n\t\t\tNotes << endl;\n\t\t\tNotes.close();\n\t\t}\n\t}\n\telse\n\t{\n\t\tifstream Notes(note_file, ios::in);\n\t\tstring line;\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\twhile(!Notes.eof())\n\t\t\t{\n\t\t\t\tgetline(Notes, line);\n\t\t\t\tcout << line << endl;\n\t\t\t}\n\t\t\tNotes.close();\n\t\t}\n\t}\n}\n"}
{"id": 44004, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "C++": "#include <fstream>\n#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char **argv)\n{\n\tif(argc>1)\n\t{\n\t\tofstream Notes(note_file, ios::app);\n\t\ttime_t timer = time(NULL);\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\tNotes << asctime(localtime(&timer)) << '\\t';\n\t\t\tfor(int i=1;i<argc;i++)\n\t\t\t\tNotes << argv[i] << ' ';\n\t\t\tNotes << endl;\n\t\t\tNotes.close();\n\t\t}\n\t}\n\telse\n\t{\n\t\tifstream Notes(note_file, ios::in);\n\t\tstring line;\n\t\tif(Notes.is_open())\n\t\t{\n\t\t\twhile(!Notes.eof())\n\t\t\t{\n\t\t\t\tgetline(Notes, line);\n\t\t\t\tcout << line << endl;\n\t\t\t}\n\t\t\tNotes.close();\n\t\t}\n\t}\n}\n"}
{"id": 44005, "name": "Thiele's interpolation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n", "C++": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string.h>\n\nconstexpr unsigned int N = 32u;\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\nconstexpr unsigned int N2 = N * (N - 1u) / 2u;\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\ndouble ρ(double *x, double *y, double *r, int i, int n) {\n    if (n < 0)\n        return 0;\n    if (!n)\n        return y[i];\n\n    unsigned int idx = (N - 1 - n) * (N - n) / 2 + i;\n    if (r[idx] != r[idx])\n        r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2);\n    return r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, unsigned int n) {\n    return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\ninline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); }\ninline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); }\ninline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); }\n\nint main() {\n    constexpr double step = .05;\n    for (auto i = 0u; i < N; i++) {\n        xval[i] = i * step;\n        t_sin[i] = sin(xval[i]);\n        t_cos[i] = cos(xval[i]);\n        t_tan[i] = t_sin[i] / t_cos[i];\n    }\n    for (auto i = 0u; i < N2; i++)\n        r_sin[i] = r_cos[i] = r_tan[i] = NAN;\n\n    std::cout << std::setw(16) << std::setprecision(25)\n              << 6 * i_sin(.5) << std::endl\n              << 3 * i_cos(.5) << std::endl\n              << 4 * i_tan(1.) << std::endl;\n\n    return 0;\n}\n"}
{"id": 44006, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n"}
{"id": 44007, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n"}
{"id": 44008, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "C++": "#include <string>\n#include <map>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\ndouble log2( double number ) {\n   return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n   std::map<char , int> frequencies ;\n   std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n   int numlen = fiboword.length( ) ;\n   double infocontent = 0 ;\n   for ( std::pair<char , int> p : frequencies ) {\n      double freq = static_cast<double>( p.second ) / numlen ;\n      infocontent += freq * log2( freq ) ;\n   }\n   infocontent *= -1 ;\n   return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n   std::cout << std::setw( 5 ) << std::left << n ;\n   std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n   std::cout << \"  \" << std::setw( 16 ) << std::setprecision( 13 ) \n      << std::left << find_entropy( fiboword ) ;\n   std::cout << \"\\n\" ;\n}\n\nint main( ) {\n   std::cout << std::setw( 5 ) << std::left << \"N\" ;\n   std::cout << std::setw( 12 ) << std::right << \"length\" ;\n   std::cout << \"  \" << std::setw( 16 ) << std::left << \"entropy\" ; \n   std::cout << \"\\n\" ;\n   std::string firststring ( \"1\" ) ;\n   int n = 1 ;\n   printLine( firststring , n ) ;\n   std::string secondstring( \"0\" ) ;\n   n++ ;\n   printLine( secondstring , n ) ;\n   while ( n < 37 ) {\n      std::string resultstring = firststring + secondstring ;\n      firststring.assign( secondstring ) ;\n      secondstring.assign( resultstring ) ;\n      n++ ;\n      printLine( resultstring , n ) ;\n   }\n   return 0 ;\n}\n"}
{"id": 44009, "name": "Angles (geometric), normalization and conversion", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n", "C++": "#include <functional>\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <sstream>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n\ntemplate<typename T>\nT normalize(T a, double b) { return std::fmod(a, b); }\n\ninline double d2d(double a) { return normalize<double>(a, 360); }\ninline double g2g(double a) { return normalize<double>(a, 400); }\ninline double m2m(double a) { return normalize<double>(a, 6400); }\ninline double r2r(double a) { return normalize<double>(a, 2*M_PI); }\n\ndouble d2g(double a) { return g2g(a * 10 / 9); }\ndouble d2m(double a) { return m2m(a * 160 / 9); }\ndouble d2r(double a) { return r2r(a * M_PI / 180); }\ndouble g2d(double a) { return d2d(a * 9 / 10); }\ndouble g2m(double a) { return m2m(a * 16); }\ndouble g2r(double a) { return r2r(a * M_PI / 200); }\ndouble m2d(double a) { return d2d(a * 9 / 160); }\ndouble m2g(double a) { return g2g(a / 16); }\ndouble m2r(double a) { return r2r(a * M_PI / 3200); }\ndouble r2d(double a) { return d2d(a * 180 / M_PI); }\ndouble r2g(double a) { return g2g(a * 200 / M_PI); }\ndouble r2m(double a) { return m2m(a * 3200 / M_PI); }\n\nvoid print(const std::vector<double> &values, const char *s, std::function<double(double)> f) {\n    using namespace std;\n    ostringstream out;\n    out << \"                  ┌───────────────────┐\\n\";\n    out << \"                  │ \" << setw(17) << s << \" │\\n\";\n    out << \"┌─────────────────┼───────────────────┤\\n\";\n    for (double i : values)\n        out << \"│ \" << setw(15) << fixed << i << defaultfloat << \" │ \" << setw(17) << fixed << f(i) << defaultfloat << \" │\\n\";\n    out << \"└─────────────────┴───────────────────┘\\n\";\n    auto str = out.str();\n    boost::algorithm::replace_all(str, \".000000\", \"       \");\n    cout << str;\n}\n\nint main() {\n    std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 };\n    print(values, \"normalized (deg)\", d2d);\n    print(values, \"normalized (grad)\", g2g);\n    print(values, \"normalized (mil)\", m2m);\n    print(values, \"normalized (rad)\", r2r);\n\n    print(values, \"deg -> grad \", d2g);\n    print(values, \"deg -> mil \", d2m);\n    print(values, \"deg -> rad \", d2r);\n\n    print(values, \"grad -> deg \", g2d);\n    print(values, \"grad -> mil \", g2m);\n    print(values, \"grad -> rad \", g2r);\n\n    print(values, \"mil -> deg \", m2d);\n    print(values, \"mil -> grad \", m2g);\n    print(values, \"mil -> rad \", m2r);\n\n    print(values, \"rad -> deg \", r2d);\n    print(values, \"rad -> grad \", r2g);\n    print(values, \"rad -> mil \", r2m);\n\n    return 0;\n}\n"}
{"id": 44010, "name": "Find common directory path", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::string longestPath( const std::vector<std::string> & , char ) ;\n\nint main( ) {\n   std::string dirs[ ] = {\n      \"/home/user1/tmp/coverage/test\" ,\n      \"/home/user1/tmp/covert/operator\" ,\n      \"/home/user1/tmp/coven/members\" } ;\n   std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;\n   std::cout << \"The longest common path of the given directories is \"\n             << longestPath( myDirs , '/' ) << \"!\\n\" ;\n   return 0 ;\n}\n\nstd::string longestPath( const std::vector<std::string> & dirs , char separator ) {\n   std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;\n   int maxCharactersCommon = vsi->length( ) ;\n   std::string compareString = *vsi ;\n   for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {\n      std::pair<std::string::const_iterator , std::string::const_iterator> p = \n\t std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;\n      if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) \n\t maxCharactersCommon = p.first - compareString.begin( ) ;\n   }\n   std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;\n   return compareString.substr( 0 , found ) ;\n}\n"}
{"id": 44011, "name": "Verify distribution uniformity_Naive", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "C++": "#include <map>\n#include <iostream>\n#include <cmath>\n\ntemplate<typename F>\n bool test_distribution(F f, int calls, double delta)\n{\n  typedef std::map<int, int> distmap;\n  distmap dist;\n\n  for (int i = 0; i < calls; ++i)\n    ++dist[f()];\n\n  double mean = 1.0/dist.size();\n\n  bool good = true;\n\n  for (distmap::iterator i = dist.begin(); i != dist.end(); ++i)\n  {\n    if (std::abs((1.0 * i->second)/calls - mean) > delta)\n    {\n      std::cout << \"Relative frequency \" << i->second/(1.0*calls)\n                << \" of result \" << i->first\n                << \" deviates by more than \" << delta\n                << \" from the expected value \" << mean << \"\\n\";\n      good = false;\n    }\n  }\n\n  return good;\n}\n"}
{"id": 44012, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n"}
{"id": 44013, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "C++": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <gmpxx.h>\n\nusing integer = mpz_class;\n\nclass stirling2 {\npublic:\n    integer get(int n, int k);\nprivate:\n    std::map<std::pair<int, int>, integer> cache_;\n};\n\ninteger stirling2::get(int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n)\n        return 0;\n    auto p = std::make_pair(n, k);\n    auto i = cache_.find(p);\n    if (i != cache_.end())\n        return i->second;\n    integer s = k * get(n - 1, k) + get(n - 1, k - 1);\n    cache_.emplace(p, s);\n    return s;\n}\n\nvoid print_stirling_numbers(stirling2& s2, int n) {\n    std::cout << \"Stirling numbers of the second kind:\\nn/k\";\n    for (int j = 0; j <= n; ++j) {\n        std::cout << std::setw(j == 0 ? 2 : 8) << j;\n    }\n    std::cout << '\\n';\n    for (int i = 0; i <= n; ++i) {\n        std::cout << std::setw(2) << i << ' ';\n        for (int j = 0; j <= i; ++j)\n            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);\n        std::cout << '\\n';\n    }\n}\n\nint main() {\n    stirling2 s2;\n    print_stirling_numbers(s2, 12);\n    std::cout << \"Maximum value of S2(n,k) where n == 100:\\n\";\n    integer max = 0;\n    for (int k = 0; k <= 100; ++k)\n        max = std::max(max, s2.get(100, k));\n    std::cout << max << '\\n';\n    return 0;\n}\n"}
{"id": 44014, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n"}
{"id": 44015, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "C++": "#include <iostream>\n#include <ostream>\n#include <set>\n#include <vector>\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {\n    auto i = v.cbegin();\n    auto e = v.cend();\n    os << '[';\n    if (i != e) {\n        os << *i;\n        i = std::next(i);\n    }\n    while (i != e) {\n        os << \", \" << *i;\n        i = std::next(i);\n    }\n    return os << ']';\n}\n\nint main() {\n    using namespace std;\n\n    vector<int> a{ 0 };\n    set<int> used{ 0 };\n    set<int> used1000{ 0 };\n    bool foundDup = false;\n    int n = 1;\n    while (n <= 15 || !foundDup || used1000.size() < 1001) {\n        int next = a[n - 1] - n;\n        if (next < 1 || used.find(next) != used.end()) {\n            next += 2 * n;\n        }\n        bool alreadyUsed = used.find(next) != used.end();\n        a.push_back(next);\n        if (!alreadyUsed) {\n            used.insert(next);\n            if (0 <= next && next <= 1000) {\n                used1000.insert(next);\n            }\n        }\n        if (n == 14) {\n            cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n        }\n        if (!foundDup && alreadyUsed) {\n            cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n            foundDup = true;\n        }\n        if (used1000.size() == 1001) {\n            cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n        }\n        n++;\n    }\n\n    return 0;\n}\n"}
{"id": 44016, "name": "Memory allocation", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n", "C++": "#include <string>\n\nint main()\n{\n  int* p;\n\n  p = new int;    \n  delete p;       \n\n  p = new int(2); \n  delete p;       \n\n  std::string* p2;\n\n  p2 = new std::string; \n  delete p2;            \n\n  p = new int[10]; \n  delete[] p;      \n\n  p2 = new std::string[10]; \n  delete[] p2;              \n}\n"}
{"id": 44017, "name": "Tic-tac-toe", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n", "C++": "#include <windows.h>\n#include <iostream>\n#include <string>\n\n\nusing namespace std;\n\n\nenum players { Computer, Human, Draw, None };\nconst int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };\n\n\nclass ttt\n{\npublic:\n    ttt() { _p = rand() % 2; reset(); }\n\n    void play()\n    {\n\tint res = Draw;\n\twhile( true )\n\t{\n\t    drawGrid();\n\t    while( true )\n\t    {\n\t\tif( _p ) getHumanMove();\n\t\telse getComputerMove();\n\n\t\tdrawGrid();\n\n\t\tres = checkVictory();\n\t\tif( res != None ) break;\n\n\t\t++_p %= 2;\n\t    }\n\n\t    if( res == Human ) cout << \"CONGRATULATIONS HUMAN --- You won!\";\n\t    else if( res == Computer ) cout << \"NOT SO MUCH A SURPRISE --- I won!\";\n\t    else cout << \"It's a draw!\";\n\n\t    cout << endl << endl;\n\n\t    string r;\n\t    cout << \"Play again( Y / N )? \"; cin >> r;\n\t    if( r != \"Y\" && r != \"y\" ) return;\n\n\t    ++_p %= 2;\n\t    reset();\n\n\t}\n    }\n\nprivate:\n    void reset() \n    {\n\tfor( int x = 0; x < 9; x++ )\n\t    _field[x] = None;\n    }\n\n    void drawGrid()\n    {\n\tsystem( \"cls\" );\n\t\t\n        COORD c = { 0, 2 };\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\n\tcout << \" 1 | 2 | 3 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 4 | 5 | 6 \" << endl;\n\tcout << \"---+---+---\" << endl;\n\tcout << \" 7 | 8 | 9 \" << endl << endl << endl;\n\n\tint f = 0;\n\tfor( int y = 0; y < 5; y += 2 )\n\t    for( int x = 1; x < 11; x += 4 )\n\t    {\n\t\tif( _field[f] != None )\n\t\t{\n\t\t    COORD c = { x, 2 + y };\n\t\t    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n\t\t    string o = _field[f] == Computer ? \"X\" : \"O\";\n\t\t    cout << o;\n\t\t}\n\t\tf++;\n\t    }\n\n        c.Y = 9;\n\tSetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );\n    }\n\n    int checkVictory()\n    {\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    if( _field[iWin[i][0]] != None &&\n\t\t_field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )\n\t    {\n\t\treturn _field[iWin[i][0]];\n\t    }\n\t}\n\n\tint i = 0;\n\tfor( int f = 0; f < 9; f++ )\n\t{\n\t    if( _field[f] != None )\n\t\ti++;\n\t}\n\tif( i == 9 ) return Draw;\n\n\treturn None;\n    }\n\n    void getHumanMove()\n    {\n\tint m;\n\tcout << \"Enter your move ( 1 - 9 ) \";\n\twhile( true )\n\t{\n\t    m = 0;\n\t    do\n\t    { cin >> m; }\n\t    while( m < 1 && m > 9 );\n\n\t    if( _field[m - 1] != None )\n\t\tcout << \"Invalid move. Try again!\" << endl;\n\t    else break;\n\t}\n\n\t_field[m - 1] = Human;\n    }\n\n    void getComputerMove()\n    {\n\tint move = 0;\n\n\tdo{ move = rand() % 9; }\n\twhile( _field[move] != None );\n\n\tfor( int i = 0; i < 8; i++ )\n\t{\n\t    int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];\n\n\t    if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )\n\t    {\n\t\tmove = try3;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) \n\t    {\t\t\t\n\t\tmove = try2;\n\t\tif( _field[try1] == Computer ) break;\n\t    }\n\n\t    if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )\n\t    {\n\t\tmove = try1;\n\t\tif( _field[try2] == Computer ) break;\n\t    }\n        }\n\t_field[move] = Computer;\n\t\t\n    }\n\n\nint _p;\nint _field[9];\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( GetTickCount() );\n\n    ttt tic;\n    tic.play();\n\n    return 0;\n}\n\n"}
{"id": 44018, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n"}
{"id": 44019, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "C++": "#include <cstdint>\n#include <iostream>\n#include <limits>\n\nint main()\n{\n  auto i = std::uintmax_t{};\n  \n  while (i < std::numeric_limits<decltype(i)>::max())\n    std::cout << ++i << '\\n';\n}\n"}
{"id": 44020, "name": "Entropy_Narcissist", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n", "C++": "#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\n\nstring readFile (string path) {\n    string contents;\n    string line;\n    ifstream inFile(path);\n    while (getline (inFile, line)) {\n        contents.append(line);\n        contents.append(\"\\n\");\n    }\n    inFile.close();\n    return contents;\n}\n\ndouble entropy (string X) {\n    const int MAXCHAR = 127;\n    int N = X.length();\n    int count[MAXCHAR];\n    double count_i;\n    char ch;\n    double sum = 0.0;\n    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;\n    for (int pos = 0; pos < N; pos++) {\n        ch = X[pos];\n        count[(int)ch]++;\n    }\n    for (int n_i = 0; n_i < MAXCHAR; n_i++) {\n        count_i = count[n_i];\n        if (count_i > 0) sum -= count_i / N * log2(count_i / N);\n    }\n    return sum;\n}\n\nint main () {\n    cout<<entropy(readFile(\"entropy.cpp\"));\n    return 0;\n}\n"}
{"id": 44021, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 44022, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 44023, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 44024, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 44025, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 44026, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 44027, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 44028, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 44029, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 44030, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 44031, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 44032, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 44033, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44034, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44035, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44036, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44037, "name": "LZW compression", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 44038, "name": "LZW compression", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 44039, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 44040, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 44041, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44042, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44043, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44044, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44045, "name": "Longest string challenge", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 44046, "name": "Longest string challenge", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 44047, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 44048, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 44049, "name": "Sorting algorithms_Strand sort", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 44050, "name": "Sorting algorithms_Strand sort", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 44051, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 44052, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 44053, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44054, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44055, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44056, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44057, "name": "Enforced immutability", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 44058, "name": "Enforced immutability", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 44059, "name": "Sutherland-Hodgman polygon clipping", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 44060, "name": "Sutherland-Hodgman polygon clipping", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 44061, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 44062, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 44063, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44064, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44065, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44066, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44067, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44068, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44069, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44070, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44071, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 44072, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 44073, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 44074, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 44075, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 44076, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 44077, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 44078, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 44079, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 44080, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 44081, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 44082, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 44083, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 44084, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 44085, "name": "Fractal tree", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 44086, "name": "Fractal tree", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 44087, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44088, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44089, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44090, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44091, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 44092, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 44093, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 44094, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 44095, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 44096, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 44097, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 44098, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 44099, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 44100, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 44101, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 44102, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 44103, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 44104, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 44105, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 44106, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 44107, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 44108, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 44109, "name": "Sorting algorithms_Shell sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 44110, "name": "Sorting algorithms_Shell sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 44111, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 44112, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 44113, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 44114, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 44115, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 44116, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 44117, "name": "Sorting algorithms_Permutation sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 44118, "name": "Sorting algorithms_Permutation sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 44119, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 44120, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 44121, "name": "Entropy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 44122, "name": "Entropy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 44123, "name": "Hello world_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n"}
{"id": 44124, "name": "Hello world_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n"}
{"id": 44125, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 44126, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 44127, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 44128, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 44129, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 44130, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 44131, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 44132, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 44133, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 44134, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 44135, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 44136, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 44137, "name": "Discordian date", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n"}
{"id": 44138, "name": "Discordian date", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n"}
{"id": 44139, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 44140, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 44141, "name": "Sorting algorithms_Patience sort", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n"}
{"id": 44142, "name": "Sorting algorithms_Patience sort", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n"}
{"id": 44143, "name": "Wireworld", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n"}
{"id": 44144, "name": "Wireworld", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n"}
{"id": 44145, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n"}
{"id": 44146, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n"}
{"id": 44147, "name": "Count occurrences of a substring", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 44148, "name": "Count occurrences of a substring", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 44149, "name": "Bitwise operations", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n"}
{"id": 44150, "name": "Dragon curve", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n"}
{"id": 44151, "name": "Read a file line by line", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n", "Python": "for line in lines open('input.txt'):\n    print line\n"}
{"id": 44152, "name": "Doubly-linked list_Element insertion", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n"}
{"id": 44153, "name": "Quickselect algorithm", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n"}
{"id": 44154, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "Python": "i = int('1a',16)  \n"}
{"id": 44155, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "Python": "i = int('1a',16)  \n"}
{"id": 44156, "name": "Walk a directory_Recursively", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n"}
{"id": 44157, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n"}
{"id": 44158, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 44159, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 44160, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n"}
{"id": 44161, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 44162, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n"}
{"id": 44163, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 44164, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n"}
{"id": 44165, "name": "LZW compression", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n"}
{"id": 44166, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 44167, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n"}
{"id": 44168, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 44169, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n"}
{"id": 44170, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 44171, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n"}
{"id": 44172, "name": "Anonymous recursion", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"}
{"id": 44173, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 44174, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n"}
{"id": 44175, "name": "Longest string challenge", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 44176, "name": "Longest string challenge", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n"}
{"id": 44177, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 44178, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n"}
{"id": 44179, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n"}
{"id": 44180, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 44181, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 44182, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n"}
{"id": 44183, "name": "Dining philosophers", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n"}
{"id": 44184, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 44185, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n"}
{"id": 44186, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 44187, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 44188, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 44189, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 44190, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n"}
{"id": 44191, "name": "Spiral matrix", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n"}
{"id": 44192, "name": "Optional parameters", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n"}
{"id": 44193, "name": "Call a foreign-language function", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n"}
{"id": 44194, "name": "Faulhaber's triangle", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n"}
{"id": 44195, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 44196, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n"}
{"id": 44197, "name": "Word wheel", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n"}
{"id": 44198, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"}
{"id": 44199, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 44200, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "Python": "   string = raw_input(\"Input a string: \")\n"}
{"id": 44201, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 44202, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n"}
{"id": 44203, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n"}
{"id": 44204, "name": "Primes - allocate descendants to their ancestors", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n"}
{"id": 44205, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 44206, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n"}
{"id": 44207, "name": "Proper divisors", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n"}
{"id": 44208, "name": "XML_Output", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n"}
{"id": 44209, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 44210, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n"}
{"id": 44211, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n"}
{"id": 44212, "name": "Hash from two arrays", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n"}
{"id": 44213, "name": "Colour pinstripe_Display", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n"}
{"id": 44214, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n"}
{"id": 44215, "name": "Animate a pendulum", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n"}
{"id": 44216, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 44217, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 44218, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n"}
{"id": 44219, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n"}
{"id": 44220, "name": "Arrays", "VB": "Option Base {0|1}\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 44221, "name": "Arrays", "VB": "Option Base {0|1}\n", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n"}
{"id": 44222, "name": "Sierpinski carpet", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n"}
{"id": 44223, "name": "Sorting algorithms_Bogosort", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n"}
{"id": 44224, "name": "Euler method", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n"}
{"id": 44225, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 44226, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n"}
{"id": 44227, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n"}
{"id": 44228, "name": "JortSort", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n"}
{"id": 44229, "name": "Leap year", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n", "Python": "import calendar\ncalendar.isleap(year)\n"}
{"id": 44230, "name": "Combinations and permutations", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n"}
{"id": 44231, "name": "Sort numbers lexicographically", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n"}
{"id": 44232, "name": "Number names", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n"}
{"id": 44233, "name": "Sorting algorithms_Shell sort", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n"}
{"id": 44234, "name": "Doubly-linked list_Definition", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n"}
{"id": 44235, "name": "Letter frequency", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n"}
{"id": 44236, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "Python": "next = str(int('123') + 1)\n"}
{"id": 44237, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "Python": "next = str(int('123') + 1)\n"}
{"id": 44238, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n"}
{"id": 44239, "name": "Averages_Arithmetic mean", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n"}
{"id": 44240, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 44241, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"}
{"id": 44242, "name": "Tokenize a string with escaping", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n"}
{"id": 44243, "name": "Forward difference", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n"}
{"id": 44244, "name": "Primality by trial division", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n"}
{"id": 44245, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n"}
{"id": 44246, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 44247, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n"}
{"id": 44248, "name": "Singly-linked list_Traversal", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n", "Python": "for node in lst:\n    print node.value\n"}
{"id": 44249, "name": "Bitmap_Write a PPM file", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n"}
{"id": 44250, "name": "Delete a file", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n"}
{"id": 44251, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 44252, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n"}
{"id": 44253, "name": "String interpolation (included)", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n"}
{"id": 44254, "name": "Determinant and permanent", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 44255, "name": "Determinant and permanent", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n"}
{"id": 44256, "name": "Ray-casting algorithm", "VB": "Imports System.Math\n\nModule RayCasting\n\n    Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}\n    Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}\n    Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}\n    Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}\n    Private shapes As Integer()()() = {square, squareHole, strange, hexagon}\n\n    Public Sub Main()\n        Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}\n\n        For Each shape As Integer()() In shapes\n            For Each point As Double() In testPoints\n                Console.Write(String.Format(\"{0} \", Contains(shape, point).ToString.PadLeft(7)))\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\n    Private Function Contains(shape As Integer()(), point As Double()) As Boolean\n\n        Dim inside As Boolean = False\n        Dim length As Integer = shape.Length\n\n        For i As Integer = 0 To length - 1\n            If Intersects(shape(i), shape((i + 1) Mod length), point) Then\n                inside = Not inside\n            End If\n        Next\n\n        Return inside\n    End Function\n\n    Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean\n\n        If a(1) > b(1) Then Return Intersects(b, a, p)\n        If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001\n        If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False\n        If p(0) < Min(a(0), b(0)) Then Return True\n        Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))\n        Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))\n\n        Return red >= blue\n    End Function\nEnd Module\n", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n"}
{"id": 44257, "name": "Count occurrences of a substring", "VB": "Function CountSubstring(str,substr)\n\tCountSubstring = 0\n\tFor i = 1 To Len(str)\n\t\tIf Len(str) >= Len(substr) Then\n\t\t\tIf InStr(i,str,substr) Then\n\t\t\t\tCountSubstring = CountSubstring + 1\n\t\t\t\ti = InStr(i,str,substr) + Len(substr) - 1\n\t\t\tEnd If\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write CountSubstring(\"the three truths\",\"th\") & vbCrLf\nWScript.StdOut.Write CountSubstring(\"ababababab\",\"abab\") & vbCrLf\n", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n"}
{"id": 44258, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 44259, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 44260, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n"}
{"id": 44261, "name": "Take notes on the command line", "VB": "Imports System.IO\n\nModule Notes\n    Function Main(ByVal cmdArgs() As String) As Integer\n        Try\n            If cmdArgs.Length = 0 Then\n                Using sr As New StreamReader(\"NOTES.TXT\")\n                    Console.WriteLine(sr.ReadToEnd)\n                End Using\n            Else\n                Using sw As New StreamWriter(\"NOTES.TXT\", True)\n                    sw.WriteLine(Date.Now.ToString())\n                    sw.WriteLine(\"{0}{1}\", ControlChars.Tab, String.Join(\" \", cmdArgs))\n                End Using\n            End If\n        Catch\n        End Try\n    End Function\nEnd Module\n", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n"}
{"id": 44262, "name": "Find common directory path", "VB": "Public Function CommonDirectoryPath(ParamArray Paths()) As String\nDim v As Variant\nDim Path() As String, s As String\nDim i As Long, j As Long, k As Long\nConst PATH_SEPARATOR As String = \"/\"\n  \n  For Each v In Paths\n    ReDim Preserve Path(0 To i)\n    Path(i) = v\n    i = i + 1\n  Next v\n  \n  k = 1\n  \n  Do\n    For i = 0 To UBound(Path)\n      If i Then\n        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then\n          Exit Do\n        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then\n          Exit Do\n        End If\n      Else\n        j = InStr(k, Path(i), PATH_SEPARATOR)\n        If j = 0 Then\n          Exit Do\n        End If\n      End If\n    Next i\n    s = Left$(Path(0), j + CLng(k <> 1))\n    k = j + 1\n  Loop\n  CommonDirectoryPath = s\n  \nEnd Function\n\nSub Main()\n\n\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/home/user1/tmp\"\n \n Debug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\", _\n \"/home/user1/abc/coven/members\") = _\n \"/home/user1\"\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/hope/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/\"\n\nEnd Sub\n", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n"}
{"id": 44263, "name": "Bitwise operations", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n"}
{"id": 44264, "name": "Dragon curve", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n"}
{"id": 44265, "name": "Read a file line by line", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n"}
{"id": 44266, "name": "Doubly-linked list_Element insertion", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n"}
{"id": 44267, "name": "Quickselect algorithm", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 44268, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 44269, "name": "Walk a directory_Recursively", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 44270, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 44271, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 44272, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n"}
{"id": 44273, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 44274, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 44275, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 44276, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 44277, "name": "Anonymous recursion", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n"}
{"id": 44278, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 44279, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 44280, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 44281, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n"}
{"id": 44282, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 44283, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 44284, "name": "Spiral matrix", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n"}
{"id": 44285, "name": "Faulhaber's triangle", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 44286, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 44287, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 44288, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 44289, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n"}
{"id": 44290, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 44291, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 44292, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 44293, "name": "Proper divisors", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 44294, "name": "XML_Output", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n"}
{"id": 44295, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n"}
{"id": 44296, "name": "Hash from two arrays", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n"}
{"id": 44297, "name": "Animate a pendulum", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n"}
{"id": 44298, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 44299, "name": "Sierpinski carpet", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n"}
{"id": 44300, "name": "Sorting algorithms_Bogosort", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 44301, "name": "Euler method", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 44302, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 44303, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 44304, "name": "JortSort", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n"}
{"id": 44305, "name": "Leap year", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n"}
{"id": 44306, "name": "Sort numbers lexicographically", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n"}
{"id": 44307, "name": "Number names", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n"}
{"id": 44308, "name": "Letter frequency", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 44309, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 44310, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 44311, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 44312, "name": "Averages_Arithmetic mean", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n"}
{"id": 44313, "name": "Tokenize a string with escaping", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n"}
{"id": 44314, "name": "Hello world_Text", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 44315, "name": "Forward difference", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 44316, "name": "Primality by trial division", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 44317, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 44318, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 44319, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 44320, "name": "Singly-linked list_Traversal", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n"}
{"id": 44321, "name": "Bitmap_Write a PPM file", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 44322, "name": "Delete a file", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n"}
{"id": 44323, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 44324, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 44325, "name": "String interpolation (included)", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n"}
{"id": 44326, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 44327, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 44328, "name": "Numbers with prime digits whose sum is 13", "VB": "Imports System\nImports System.Console\nImports LI = System.Collections.Generic.SortedSet(Of Integer)\n\nModule Module1 \n    Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI\n        If lft = 0 Then\n            res.Add(vlu)\n        ElseIf lft > 0 Then\n            For Each itm As Integer In lst\n                res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)\n            Next\n        End If\n        Return res\n    End Function\n\n    Sub Main(ByVal args As String())\n        WriteLine(string.Join(\" \",\n            unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))\n    End Sub\nEnd Module\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 44329, "name": "Take notes on the command line", "VB": "Imports System.IO\n\nModule Notes\n    Function Main(ByVal cmdArgs() As String) As Integer\n        Try\n            If cmdArgs.Length = 0 Then\n                Using sr As New StreamReader(\"NOTES.TXT\")\n                    Console.WriteLine(sr.ReadToEnd)\n                End Using\n            Else\n                Using sw As New StreamWriter(\"NOTES.TXT\", True)\n                    sw.WriteLine(Date.Now.ToString())\n                    sw.WriteLine(\"{0}{1}\", ControlChars.Tab, String.Join(\" \", cmdArgs))\n                End Using\n            End If\n        Catch\n        End Try\n    End Function\nEnd Module\n", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n"}
{"id": 44330, "name": "Find common directory path", "VB": "Public Function CommonDirectoryPath(ParamArray Paths()) As String\nDim v As Variant\nDim Path() As String, s As String\nDim i As Long, j As Long, k As Long\nConst PATH_SEPARATOR As String = \"/\"\n  \n  For Each v In Paths\n    ReDim Preserve Path(0 To i)\n    Path(i) = v\n    i = i + 1\n  Next v\n  \n  k = 1\n  \n  Do\n    For i = 0 To UBound(Path)\n      If i Then\n        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then\n          Exit Do\n        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then\n          Exit Do\n        End If\n      Else\n        j = InStr(k, Path(i), PATH_SEPARATOR)\n        If j = 0 Then\n          Exit Do\n        End If\n      End If\n    Next i\n    s = Left$(Path(0), j + CLng(k <> 1))\n    k = j + 1\n  Loop\n  CommonDirectoryPath = s\n  \nEnd Function\n\nSub Main()\n\n\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/home/user1/tmp\"\n \n Debug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/home/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\", _\n \"/home/user1/abc/coven/members\") = _\n \"/home/user1\"\n\nDebug.Assert CommonDirectoryPath( _\n \"/home/user1/tmp/coverage/test\", _\n \"/hope/user1/tmp/covert/operator\", _\n \"/home/user1/tmp/coven/members\") = _\n \"/\"\n\nEnd Sub\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n"}
{"id": 44331, "name": "Recaman's sequence", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 44332, "name": "Recaman's sequence", "VB": "\n\tnx=15\n\th=1000\n\tWscript.StdOut.WriteLine \"Recaman\n\tWscript.StdOut.WriteLine recaman(\"seq\",nx)\n\tWscript.StdOut.WriteLine \"The first duplicate number is: \" & recaman(\"firstdup\",0)\n\tWscript.StdOut.WriteLine \"The number of terms to complete the range 0--->\"& h &\" is: \"& recaman(\"numterm\",h)\n\tWscript.StdOut.Write vbCrlf&\".../...\": zz=Wscript.StdIn.ReadLine()\n\t\nfunction recaman(op,nn)\n\tDim b,d,h\n\tSet b = CreateObject(\"Scripting.Dictionary\")\n\tSet d = CreateObject(\"Scripting.Dictionary\")\n    list=\"0\" : firstdup=0\n\tif op=\"firstdup\" then\n\t\tnn=1000 : firstdup=1\n\tend if\n\tif op=\"numterm\" then\n\t\th=nn : nn=10000000 : numterm=1\n\tend if\n\tax=0  \n\tb.Add 0,1  \n\ts=0\n\tfor n=1 to nn-1\n        an=ax-n\n\t\tif an<=0 then \n\t\t\tan=ax+n\n\t\telseif b.Exists(an) then \n\t\t\tan=ax+n\n\t\tend if\n\t\tax=an  \n\t\tif not b.Exists(an) then b.Add an,1  \n\t\tif op=\"seq\" then\n\t\t\tlist=list&\" \"&an\n\t\tend if\n\t\tif firstdup then\n\t\t\tif d.Exists(an) then\n\t\t\t\trecaman=\"a(\"&n&\")=\"&an\n\t\t\t\texit function\n\t\t\telse\n\t\t\t\td.Add an,1  \n\t\t\tend if\n\t\tend if\n\t\tif numterm then\n\t\t\tif an<=h then\n\t\t\t\tif not d.Exists(an) then\n\t\t\t\t\ts=s+1\n\t\t\t\t\td.Add an,1  \n\t\t\t\tend if\n\t\t\t\tif s>=h then\n\t\t\t\t\trecaman=n\n\t\t\t\t\texit function\n\t\t\t\tend if\n\t\t\tend if\n\t\tend if\n\tnext \n\trecaman=list\nend function \n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 44333, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n"}
{"id": 44334, "name": "Dragon curve", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n"}
{"id": 44335, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n"}
{"id": 44336, "name": "Doubly-linked list_Element insertion", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n"}
{"id": 44337, "name": "Smarandache prime-digital sequence", "Python": "def divisors(n):\n    divs = [1]\n    for ii in range(2, int(n ** 0.5) + 3):\n        if n % ii == 0:\n            divs.append(ii)\n            divs.append(int(n / ii))\n    divs.append(n)\n    return list(set(divs))\n\n\ndef is_prime(n):\n    return len(divisors(n)) == 2\n\n\ndef digit_check(n):\n    if len(str(n))<2:\n        return True\n    else:\n        for digit in str(n):\n            if not is_prime(int(digit)):\n                return False\n        return True\n\n\ndef sequence(max_n=None):\n    ii = 0\n    n = 0\n    while True:\n        ii += 1\n        if is_prime(ii):\n            if max_n is not None:\n                if n>max_n:\n                    break\n            if digit_check(ii):\n                n += 1\n                yield ii\n\n\nif __name__ == '__main__':\n    generator = sequence(100)\n    for index, item in zip(range(1, 16), generator):\n        print(index, item)\n    for index, item in zip(range(16, 100), generator):\n        pass\n    print(100, generator.__next__())\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n"}
{"id": 44338, "name": "Quickselect algorithm", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n"}
{"id": 44339, "name": "Non-decimal radices_Convert", "Python": "i = int('1a',16)  \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n"}
{"id": 44340, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n"}
{"id": 44341, "name": "Main step of GOST 28147-89", "Python": "k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype sBox [8][16]byte\n\ntype gost struct {\n    k87, k65, k43, k21 [256]byte\n    enc                []byte\n}\n\nfunc newGost(s *sBox) *gost {\n    var g gost\n    for i := range g.k87 {\n        g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]\n        g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]\n        g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]\n        g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]\n    }\n    g.enc = make([]byte, 8)\n    return &g\n}\n\nfunc (g *gost) f(x uint32) uint32 {\n    x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |\n        uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])\n    return x<<11 | x>>(32-11)\n}\n\n\n\n\n\n\nvar cbrf = sBox{\n    {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},\n    {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},\n    {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},\n    {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},\n    {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},\n    {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},\n    {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},\n    {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},\n}\n\nfunc u32(b []byte) uint32 {\n    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc b4(u uint32, b []byte) {\n    b[0] = byte(u)\n    b[1] = byte(u >> 8)\n    b[2] = byte(u >> 16)\n    b[3] = byte(u >> 24)\n}\n\nfunc (g *gost) mainStep(input []byte, key []byte) {\n    key32 := u32(key)\n    input1 := u32(input[:4])\n    input2 := u32(input[4:])\n    b4(g.f(key32+input1)^input2, g.enc[:4])\n    copy(g.enc[4:], input[:4])\n}\n\nfunc main() {\n    input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}\n    key := []byte{0xF9, 0x04, 0xC1, 0xE2}\n\n    g := newGost(&cbrf)\n    g.mainStep(input, key)\n    for _, b := range g.enc {\n        fmt.Printf(\"[%02x]\", b)\n    }\n    fmt.Println()\n}\n"}
{"id": 44342, "name": "State name puzzle", "Python": "from collections import defaultdict\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n\"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\", \"Kansas\",\n\"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n\"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n\"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n\"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n\n\n]\n\nstates = sorted(set(states))\n\nsmap = defaultdict(list)\nfor i, s1 in enumerate(states[:-1]):\n    for s2 in states[i + 1:]:\n        smap[\"\".join(sorted(s1 + s2))].append(s1 + \" + \" + s2)\n\nfor pairs in sorted(smap.itervalues()):\n    if len(pairs) > 1:\n        print \" = \".join(pairs)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n"}
{"id": 44343, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n"}
{"id": 44344, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 44345, "name": "CSV to HTML translation", "Python": "csvtxt = \n\nfrom cgi import escape\n\ndef _row2tr(row, attr=None):\n    cols = escape(row).split(',')\n    return ('<TR>'\n            + ''.join('<TD>%s</TD>' % data for data in cols)\n            + '</TR>')\n\ndef csv2html(txt):\n    htmltxt = '<TABLE summary=\"csv2html program output\">\\n'\n    for rownum, row in enumerate(txt.split('\\n')):\n        htmlrow = _row2tr(row)\n        htmlrow = '  <TBODY>%s</TBODY>\\n' % htmlrow\n        htmltxt += htmlrow\n    htmltxt += '</TABLE>\\n'\n    return htmltxt\n\nhtmltxt = csv2html(csvtxt)\nprint(htmltxt)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n"}
{"id": 44346, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n"}
{"id": 44347, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 44348, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n"}
{"id": 44349, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n"}
{"id": 44350, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 44351, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n"}
{"id": 44352, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 44353, "name": "Magic squares of odd order", "Python": ">>> def magic(n):\n    for row in range(1, n + 1):\n        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n                       (n * ((row + col - 1 + n // 2) % n) +\n                       ((row + 2 * col - 2) % n) + 1\n                       for col in range(1, n + 1))))\n    print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n    \n>>> for n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n\n\t\n\nOrder 5\n=======\n17 24  1  8 15\n23  5  7 14 16\n 4  6 13 20 22\n10 12 19 21  3\n11 18 25  2  9\n\nAll sum to magic number 65\n\nOrder 3\n=======\n8 1 6\n3 5 7\n4 9 2\n\nAll sum to magic number 15\n\nOrder 7\n=======\n30 39 48  1 10 19 28\n38 47  7  9 18 27 29\n46  6  8 17 26 35 37\n 5 14 16 25 34 36 45\n13 15 24 33 42 44  4\n21 23 32 41 43  3 12\n22 31 40 49  2 11 20\n\nAll sum to magic number 175\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 44354, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 44355, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 44356, "name": "Yellowstone sequence", "Python": "\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n\ndef yellowstone():\n    \n    \n    def relativelyPrime(a):\n        return lambda b: 1 == gcd(a, b)\n\n    \n    def nextWindow(triple):\n        p2, p1, rest = triple\n        [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n        \n        def match(xxs):\n            x, xs = uncons(xxs)['Just']\n            return (x, xs) if rp1(x) and not rp2(x) else (\n                second(cons(x))(\n                    match(xs)\n                )\n            )\n        n, residue = match(rest)\n        return (p1, n, residue)\n\n    return chain(\n        range(1, 3),\n        map(\n            itemgetter(1),\n            iterate(nextWindow)(\n                (2, 3, count(4))\n            )\n        )\n    )\n\n\n\n\ndef main():\n    \n\n    print(showList(\n        take(30)(yellowstone())\n    ))\n    pyplot.plot(\n        take(100)(yellowstone())\n    )\n    pyplot.xlabel(main.__doc__)\n    pyplot.show()\n\n\n\n\n\ndef Just(x):\n    \n    return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n\ndef Nothing():\n    \n    return {'type': 'Maybe', 'Nothing': True}\n\n\n\ndef cons(x):\n    \n    return lambda xs: [x] + xs if (\n        isinstance(xs, list)\n    ) else x + xs if (\n        isinstance(xs, str)\n    ) else chain([x], xs)\n\n\n\ndef iterate(f):\n    \n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n\ndef second(f):\n    \n    return lambda xy: (xy[0], f(xy[1]))\n\n\n\ndef showList(xs):\n    \n    return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n\n\ndef take(n):\n    \n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, (list, tuple))\n        else list(islice(xs, n))\n    )\n\n\n\ndef uncons(xs):\n    \n    if isinstance(xs, list):\n        return Just((xs[0], xs[1:])) if xs else Nothing()\n    else:\n        nxt = take(1)(xs)\n        return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n"}
{"id": 44357, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 44358, "name": "Cut a rectangle", "Python": "def cut_it(h, w):\n    dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))\n    if h % 2: h, w = w, h\n    if h % 2: return 0\n    if w == 1: return 1\n    count = 0\n\n    next = [w + 1, -w - 1, -1, 1]\n    blen = (h + 1) * (w + 1) - 1\n    grid = [False] * (blen + 1)\n\n    def walk(y, x, count):\n        if not y or y == h or not x or x == w:\n            return count + 1\n\n        t = y * (w + 1) + x\n        grid[t] = grid[blen - t] = True\n\n        if not grid[t + next[0]]:\n            count = walk(y + dirs[0][0], x + dirs[0][1], count)\n        if not grid[t + next[1]]:\n            count = walk(y + dirs[1][0], x + dirs[1][1], count)\n        if not grid[t + next[2]]:\n            count = walk(y + dirs[2][0], x + dirs[2][1], count)\n        if not grid[t + next[3]]:\n            count = walk(y + dirs[3][0], x + dirs[3][1], count)\n\n        grid[t] = grid[blen - t] = False\n        return count\n\n    t = h // 2 * (w + 1) + w // 2\n    if w % 2:\n        grid[t] = grid[t + 1] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        res = count\n        count = 0\n        count = walk(h // 2 - 1, w // 2, count)\n        return res + count * 2\n    else:\n        grid[t] = True\n        count = walk(h // 2, w // 2 - 1, count)\n        if h == w:\n            return count * 2\n        count = walk(h // 2 - 1, w // 2, count)\n        return count\n\ndef main():\n    for w in xrange(1, 10):\n        for h in xrange(1, w + 1):\n            if not((w * h) % 2):\n                print \"%d x %d: %d\" % (w, h, cut_it(w, h))\n\nmain()\n", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n"}
{"id": 44359, "name": "Mertens function", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n"}
{"id": 44360, "name": "Mertens function", "Python": "def mertens(count):\n    \n    m = [None, 1]\n    for n in range(2, count+1):\n        m.append(1)\n        for k in range(2, n+1):\n            m[n] -= m[n//k]\n    return m\n    \n\nms = mertens(1000)\n\nprint(\"The first 99 Mertens numbers are:\")\nprint(\"  \", end=' ')\ncol = 1\nfor n in ms[1:100]:\n    print(\"{:2d}\".format(n), end=' ')\n    col += 1\n    if col == 10:\n        print()\n        col = 0\n        \nzeroes = sum(x==0 for x in ms)\ncrosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))\nprint(\"M(N) equals zero {} times.\".format(zeroes))\nprint(\"M(N) crosses zero {} times.\".format(crosses))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n"}
{"id": 44361, "name": "Order by pair comparisons", "Python": "def _insort_right(a, x, q):\n    \n\n    lo, hi = 0, len(a)\n    while lo < hi:\n        mid = (lo+hi)//2\n        q += 1\n        less = input(f\"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: \").strip().lower() == 'y'\n        if less: hi = mid\n        else: lo = mid+1\n    a.insert(lo, x)\n    return q\n\ndef order(items):\n    ordered, q = [], 0\n    for item in items:\n        q = _insort_right(ordered, item, q)\n    return ordered, q\n\nif __name__ == '__main__':\n    items = 'violet red green indigo blue yellow orange'.split()\n    ans, questions = order(items)\n    print('\\n' + ' '.join(ans))\n", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n"}
{"id": 44362, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 44363, "name": "Benford's law", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n    a,b = 1,1\n    while True:\n        yield a\n        a,b = b,a+b\n\n\ndef power_of_threes():\n    return (3**k for k in count(0))\n\ndef heads(s):\n    for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n    c = Counter(s)\n    size = sum(c.values())\n    res = [c[d]/size for d in range(1,10)]\n\n    print(\"\\n%s Benfords deviation\" % title)\n    for r, e in zip(res, expected):\n        print(\"%5.1f%% %5.1f%%  %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n    while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n    show_dist(\"fibbed\", islice(heads(fib()), 1000))\n    show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n    \n    show_dist(\"random\", islice(heads(rand1000()), 10000))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n"}
{"id": 44364, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 44365, "name": "Nautical bell", "Python": "import time, calendar, sched, winsound\n\nduration = 750      \nfreq = 1280         \nbellchar = \"\\u2407\"\nwatches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')\n\ndef gap(n=1):\n    time.sleep(n * duration / 1000)\noff = gap\n \ndef on(n=1):\n    winsound.Beep(freq, n * duration)\n \ndef bong():\n    on(); off(0.5)\n\ndef bongs(m):\n    for i in range(m):\n        print(bellchar, end=' ')\n        bong()\n        if i % 2:\n            print('  ', end='')\n            off(0.5)\n    print('')\n        \nscheds =  sched.scheduler(time.time, time.sleep)\n\ndef ships_bell(now=None):\n    def adjust_to_half_hour(atime):\n        atime[4] = (atime[4] // 30) * 30\n        atime[5] = 0\n        return atime\n\n    debug = now is not None\n    rightnow = time.gmtime()\n    if not debug:\n        now = adjust_to_half_hour( list(rightnow) )\n    then = now[::]\n    then[4] += 30\n    hr, mn = now[3:5]\n    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)\n    b += 1\n    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')\n    if debug:\n        print(\"%02i:%02i, %-20s %s\" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')\n    else:\n        print(\"%02i:%02i, %-20s %s\" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')\n    bongs(b)\n    if not debug:\n        scheds.enterabs(calendar.timegm(then), 0, ships_bell)\n        \n        scheds.run()\n\ndef dbg_tester():\n    for h in range(24):\n        for m in (0, 30):\n            if (h,m) == (24,30): break\n            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )\n        \n    \nif __name__ == '__main__':\n    ships_bell()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n"}
{"id": 44366, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n"}
{"id": 44367, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 44368, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 44369, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n"}
{"id": 44370, "name": "Legendre prime counting function", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n    res = 0\n    while True:\n        if not a or not x:\n            return x + res\n    \n        a -= 1\n        res -= phi(x//p[a], a) \n\ndef legpi(n):\n    if n < 2: return 0\n\n    a = legpi(isqrt(n))\n    return phi(n, a) + a - 1\n\nfor e in range(10):\n    print(f'10^{e}', legpi(10**e))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n"}
{"id": 44371, "name": "Use another language to call a function", "Python": "\n\ndef query(buffer_length):\n    message = b'Here am I'\n    L = len(message)\n    return message[0:L*(L <= buffer_length)]\n", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n"}
{"id": 44372, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n"}
{"id": 44373, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 44374, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 44375, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n"}
{"id": 44376, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n"}
{"id": 44377, "name": "Unprimeable numbers", "Python": "from itertools import count, islice\n\ndef primes(_cache=[2, 3]):\n    yield from _cache\n    for n in count(_cache[-1]+2, 2):\n        if isprime(n):\n            _cache.append(n)\n            yield n\n\ndef isprime(n, _seen={0: False, 1: False}):\n    def _isprime(n):\n        for p in primes():\n            if p*p > n:\n                return True\n            if n%p == 0:\n                return False\n\n    if n not in _seen:\n        _seen[n] = _isprime(n)\n    return _seen[n]\n\ndef unprime():\n    for a in count(1):\n        d = 1\n        while d <= a:\n            base = (a//(d*10))*(d*10) + (a%d) \n            if any(isprime(y) for y in range(base, base + d*10, d)):\n                break\n            d *= 10\n        else:\n            yield a\n\n\nprint('First 35:')\nprint(' '.join(str(i) for i in islice(unprime(), 35)))\n\nprint('\\nThe 600-th:')\nprint(list(islice(unprime(), 599, 600))[0])\nprint()\n\nfirst, need = [False]*10, 10\nfor p in unprime():\n    i = p%10\n    if first[i]: continue\n\n    first[i] = p\n    need -= 1\n    if not need:\n        break\n\nfor i,v in enumerate(first):\n    print(f'{i} ending: {v}')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n"}
{"id": 44378, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 44379, "name": "Pascal's triangle_Puzzle", "Python": "\n\n\n\n\n\n\n\ndef combine( snl, snr ):\n\n\tcl = {}\n\tif isinstance(snl, int):\n\t\tcl['1'] = snl\n\telif isinstance(snl, string):\n\t\tcl[snl] = 1\n\telse:\n\t\tcl.update( snl)\n\n\tif isinstance(snr, int):\n\t\tn = cl.get('1', 0)\n\t\tcl['1'] = n + snr\n\telif isinstance(snr, string):\n\t\tn = cl.get(snr, 0)\n\t\tcl[snr] = n + 1\n\telse:\n\t\tfor k,v in snr.items():\n\t\t\tn = cl.get(k, 0)\n\t\t\tcl[k] = n+v\n\treturn cl\n\n\ndef constrain(nsum, vn ):\n\tnn = {}\n\tnn.update(vn)\n\tn = nn.get('1', 0)\n\tnn['1'] = n - nsum\n\treturn nn\n\ndef makeMatrix( constraints ):\n\tvmap = set()\n\tfor c in constraints:\n\t\tvmap.update( c.keys())\n\tvmap.remove('1')\n\tnvars = len(vmap)\n\tvmap = sorted(vmap)\t\t\n\tmtx = []\n\tfor c in constraints:\n\t\trow = []\n\t\tfor vv in vmap:\n\t\t\trow.append(float(c.get(vv, 0)))\n\t\trow.append(-float(c.get('1',0)))\n\t\tmtx.append(row)\n\t\n\tif len(constraints) == nvars:\n\t\tprint 'System appears solvable'\n\telif len(constraints) < nvars:\n\t\tprint 'System is not solvable - needs more constraints.'\n\treturn mtx, vmap\n\n\ndef SolvePyramid( vl, cnstr ):\n\n\tvl.reverse()\n\tconstraints = [cnstr]\n\tlvls = len(vl)\n\tfor lvln in range(1,lvls):\n\t\tlvd = vl[lvln]\n\t\tfor k in range(lvls - lvln):\n\t\t\tsn = lvd[k]\n\t\t\tll = vl[lvln-1]\n\t\t\tvn = combine(ll[k], ll[k+1])\n\t\t\tif sn is None:\n\t\t\t\tlvd[k] = vn\n\t\t\telse:\n\t\t\t\tconstraints.append(constrain( sn, vn ))\n\n\tprint 'Constraint Equations:'\n\tfor cstr in constraints:\n\t\tfset = ('%d*%s'%(v,k) for k,v in cstr.items() )\n\t\tprint ' + '.join(fset), ' = 0'\n\n\tmtx,vmap = makeMatrix(constraints)\n\n\tMtxSolve(mtx)\n\n\td = len(vmap)\n\tfor j in range(d):\n\t\tprint vmap[j],'=', mtx[j][d]\n\n\ndef MtxSolve(mtx):\n\t\n\n\tmDim = len(mtx)\t\t\t\n\tfor j in range(mDim):\n\t\trw0= mtx[j]\n\t\tf = 1.0/rw0[j]\n\t\tfor k in range(j, mDim+1):\n\t\t\trw0[k] *= f\n\t\t\n\t\tfor l in range(1+j,mDim):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\tfor k in range(j, mDim+1):\n\t\t\t\trwl[k] += f * rw0[k]\n\n\t\n\tfor j1 in range(1,mDim):\n\t\tj = mDim - j1\n\t\trw0= mtx[j]\n\t\tfor l in range(0, j):\n\t\t\trwl = mtx[l]\n\t\t\tf = -rwl[j]\n\t\t\trwl[j]    += f * rw0[j]\n\t\t\trwl[mDim] += f * rw0[mDim]\n\n\treturn mtx\n\n\np = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]\naddlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }\nSolvePyramid( p, addlConstraint)\n", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n"}
{"id": 44380, "name": "Chernick's Carmichael numbers", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n"}
{"id": 44381, "name": "Chernick's Carmichael numbers", "Python": "\n\n\n\nfrom sympy import isprime\n\n\n\ndef primality_pretest(k):\n    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):\n        return (k <= 23)\n        \n    return True\n\ndef is_chernick(n, m):\n\n    t = 9 * m\n    \n    if not primality_pretest(6 * m + 1):\n        return False\n        \n    if not primality_pretest(12 * m + 1):\n        return False\n        \n    for i in range(1,n-1):\n        if not primality_pretest((t << i) + 1):\n            return False\n        \n    if not isprime(6 * m + 1):\n        return False\n        \n    if not isprime(12 * m + 1):\n        return False\n        \n    for i in range(1,n - 1):\n        if not isprime((t << i) + 1):\n            return False\n        \n    return True\n    \nfor n in range(3,10):\n\n    if n > 4:\n        multiplier = 1 << (n - 4)\n    else:\n        multiplier = 1\n    \n    if n > 5:\n        multiplier *= 5\n        \n        \n    k = 1\n    \n    while True:\n        m = k * multiplier\n        \n        if is_chernick(n, m): \n            print(\"a(\"+str(n)+\") has m = \"+str(m))\n            break\n            \n        k += 1\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n"}
{"id": 44382, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 44383, "name": "Find if a point is within a triangle", "Python": "\n\nfrom sympy.geometry import Point, Triangle\n\ndef sign(pt1, pt2, pt3):\n    \n    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)\n\n\ndef iswithin(point, pt1, pt2, pt3):\n    \n    zval1 = sign(point, pt1, pt2)\n    zval2 = sign(point, pt2, pt3)\n    zval3 = sign(point, pt3, pt1)\n    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0\n    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0\n    return notanyneg or notanypos\n\nif __name__ == \"__main__\":\n    POINTS = [Point(0, 0)]\n    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))\n    for pnt in POINTS:\n        a, b, c = TRI.vertices\n        isornot = \"is\" if iswithin(pnt, a, b, c) else \"is not\"\n        print(\"Point\", pnt, isornot, \"within the triangle\", TRI)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n"}
{"id": 44384, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 44385, "name": "Tau function", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef tau(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= 1 + k\n    return ans\n\nif __name__ == \"__main__\":\n    print(*map(tau, range(1, 101)))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 44386, "name": "Sequence of primorial primes", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n    isprime = pyprimes.isprime\n    n, primo = 0, 1\n    for prime in pyprimes.nprimes(_pmax):\n        n, primo = n+1, primo * prime\n        if isprime(primo-1) or isprime(primo+1):\n            yield n\n        \nif __name__ == '__main__':\n    \n    pyprimes.warn_probably = False  \n    for i, n in zip(range(20), primorial_prime()):\n        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n"}
{"id": 44387, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 44388, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 44389, "name": "Bioinformatics_base count", "Python": "from collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n    \nif __name__ == '__main__':\n    print(\"SEQUENCE:\")\n    sequence = \n    seq_pp(sequence)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n"}
{"id": 44390, "name": "Dining philosophers", "Python": "import threading\nimport random\nimport time\n\n\n\n\n\n\n\n\n\n\nclass Philosopher(threading.Thread):\n    \n    running = True\n\n    def __init__(self, xname, forkOnLeft, forkOnRight):\n        threading.Thread.__init__(self)\n        self.name = xname\n        self.forkOnLeft = forkOnLeft\n        self.forkOnRight = forkOnRight\n\n    def run(self):\n        while(self.running):\n            \n            time.sleep( random.uniform(3,13))\n            print '%s is hungry.' % self.name\n            self.dine()\n\n    def dine(self):\n        fork1, fork2 = self.forkOnLeft, self.forkOnRight\n\n        while self.running:\n            fork1.acquire(True)\n            locked = fork2.acquire(False)\n            if locked: break\n            fork1.release()\n            print '%s swaps forks' % self.name\n            fork1, fork2 = fork2, fork1\n        else:\n            return\n\n        self.dining()\n        fork2.release()\n        fork1.release()\n\n    def dining(self):\t\t\t\n        print '%s starts eating '% self.name\n        time.sleep(random.uniform(1,10))\n        print '%s finishes eating and leaves to think.' % self.name\n\ndef DiningPhilosophers():\n    forks = [threading.Lock() for n in range(5)]\n    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')\n\n    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n            for i in range(5)]\n\n    random.seed(507129)\n    Philosopher.running = True\n    for p in philosophers: p.start()\n    time.sleep(100)\n    Philosopher.running = False\n    print (\"Now we're finishing.\")\n\nDiningPhilosophers()\n", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n"}
{"id": 44391, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 44392, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 44393, "name": "Factorions", "Python": "fact = [1] \nfor n in range(1, 12):\n    fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n    print(f\"The factorions for base {b} are:\")\n    for i in range(1, 1500000):\n        fact_sum = 0\n        j = i\n        while j > 0:\n            d = j % b\n            fact_sum += fact[d]\n            j = j//b\n        if fact_sum == i:\n            print(i, end=\" \")\n    print(\"\\n\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n"}
{"id": 44394, "name": "Logistic curve fitting in epidemiology", "Python": "import numpy as np\nimport scipy.optimize as opt\n\nn0, K = 27, 7_800_000_000\n\ndef f(t, r):\n    return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))\n\ny = [\n27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n105824, 109695, 114232, 118610, 125497, 133852, 143227,\n151367, 167418, 180096, 194836, 213150, 242364, 271106,\n305117, 338133, 377918, 416845, 468049, 527767, 591704,\n656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n1174652,\n]\nx = np.linspace(0.0, 96, 97)\n\nr, cov = opt.curve_fit(f, x, y, [0.5])\n\n\nprint(\"The r for the world Covid-19 data is:\", r,\n    \", with covariance of\", cov)   \nprint(\"The calculated R0 is then\", np.exp(12 * r))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n"}
{"id": 44395, "name": "Sorting algorithms_Strand sort", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n"}
{"id": 44396, "name": "Additive primes", "Python": "def is_prime(n: int) -> bool:\n    if n <= 3:\n        return n > 1\n    if n % 2 == 0 or n % 3 == 0:\n        return False\n    i = 5\n    while i ** 2 <= n:\n        if n % i == 0 or n % (i + 2) == 0:\n            return False\n        i += 6\n    return True\n\ndef digit_sum(n: int) -> int:\n    sum = 0\n    while n > 0:\n        sum += n % 10\n        n //= 10\n    return sum\n\ndef main() -> None:\n    additive_primes = 0\n    for i in range(2, 500):\n        if is_prime(i) and is_prime(digit_sum(i)):\n            additive_primes += 1\n            print(i, end=\" \")\n    print(f\"\\nFound {additive_primes} additive primes less than 500\")\n\nif __name__ == \"__main__\":\n    main()\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n"}
{"id": 44397, "name": "Inverted syntax", "Python": "x = truevalue if condition else falsevalue\n", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n"}
{"id": 44398, "name": "Inverted syntax", "Python": "x = truevalue if condition else falsevalue\n", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n"}
{"id": 44399, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 44400, "name": "Perfect totient numbers", "Python": "from math import gcd\nfrom functools import lru_cache\nfrom itertools import islice, count\n\n@lru_cache(maxsize=None)\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\ndef perfect_totient():\n    for n0 in count(1):\n        parts, n = 0, n0\n        while n != 1:\n            n = φ(n)\n            parts += n\n        if parts == n0:\n            yield n0\n        \n\nif __name__ == '__main__':\n    print(list(islice(perfect_totient(), 20)))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n"}
{"id": 44401, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n"}
{"id": 44402, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 44403, "name": "Sum of divisors", "Python": "def factorize(n):\n    assert(isinstance(n, int))\n    if n < 0: \n        n = -n \n    if n < 2: \n        return \n    k = 0 \n    while 0 == n%2: \n        k += 1 \n        n //= 2 \n    if 0 < k: \n        yield (2,k) \n    p = 3 \n    while p*p <= n: \n        k = 0 \n        while 0 == n%p: \n            k += 1 \n            n //= p \n        if 0 < k: \n            yield (p,k)\n        p += 2 \n    if 1 < n: \n        yield (n,1) \n\ndef sum_of_divisors(n): \n    assert(n != 0) \n    ans = 1 \n    for (p,k) in factorize(n): \n        ans *= (pow(p,k+1) - 1)//(p-1) \n    return ans \n    \nif __name__ == \"__main__\":\n    print([sum_of_divisors(n) for n in range(1,101)])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 44404, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 44405, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n"}
{"id": 44406, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n"}
{"id": 44407, "name": "Sutherland-Hodgman polygon clipping", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n"}
{"id": 44408, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 44409, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n"}
{"id": 44410, "name": "Spiral matrix", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n"}
{"id": 44411, "name": "Optional parameters", "Python": ">>> def printtable(data):\n    for row in data:\n        print ' '.join('%-5s' % ('\"%s\"' % cell) for cell in row)\n\n        \n>>> import operator\n>>> def sorttable(table, ordering=None, column=0, reverse=False):\n    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)\n\n>>> data = [[\"a\", \"b\", \"c\"], [\"\", \"q\", \"z\"], [\"zap\", \"zip\", \"Zot\"]]\n>>> printtable(data)\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data) )\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=2) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>> printtable( sorttable(data, column=1) )\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n\"zap\" \"zip\" \"Zot\"\n>>> printtable( sorttable(data, column=1, reverse=True) )\n\"zap\" \"zip\" \"Zot\"\n\"\"    \"q\"   \"z\"  \n\"a\"   \"b\"   \"c\"  \n>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )\n\"zap\" \"zip\" \"Zot\"\n\"a\"   \"b\"   \"c\"  \n\"\"    \"q\"   \"z\"  \n>>>\n", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n"}
{"id": 44412, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 44413, "name": "Voronoi diagram", "Python": "def setup():\n    size(500, 500)\n    generate_voronoi_diagram(width, height, 25)\n    saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n    nx, ny, nr, ng, nb = [], [], [], [], [] \n    for i in range(num_cells):\n        nx.append(int(random(w)))\n        ny.append(int(random(h)))\n        nr.append(int(random(256)))\n        ng.append(int(random(256)))\n        nb.append(int(random(256)))\n    for y in range(h):\n        for x in range(w):\n            dmin = dist(0, 0, w - 1, h - 1)\n            j = -1\n            for i in range(num_cells):\n                d = dist(0, 0, nx[i] - x, ny[i] - y)\n                if d < dmin:\n                    dmin = d\n                    j = i\n            set(x, y, color(nr[j], ng[j], nb[j]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 44414, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n"}
{"id": 44415, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 44416, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n"}
{"id": 44417, "name": "Faulhaber's triangle", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n"}
{"id": 44418, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 44419, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"}
{"id": 44420, "name": "Word wheel", "Python": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n    \"Return lowercased words of 3 to 9 characters\"\n    words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n    return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n    gridcount = Counter(grid)\n    mid = grid[4]\n    return [word for word in dictionary\n            if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n    chars = ''.join(GRID.strip().lower().split())\n    found = solve(chars, dictionary=getwords())\n    print('\\n'.join(found))\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n"}
{"id": 44421, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n"}
{"id": 44422, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n"}
{"id": 44423, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 44424, "name": "Musical scale", "Python": ">>> import winsound\n>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:\n\twinsound.Beep(int(note+.5), 500)\t\n>>>\n", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n"}
{"id": 44425, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n"}
{"id": 44426, "name": "Primes - allocate descendants to their ancestors", "Python": "from __future__ import print_function\nfrom itertools import takewhile\n\nmaxsum = 99\n\ndef get_primes(max):\n    if max < 2:\n        return []\n    lprimes = [2]\n    for x in range(3, max + 1, 2):\n        for p in lprimes:\n            if x % p == 0:\n                break\n        else:\n            lprimes.append(x)\n    return lprimes\n\ndescendants = [[] for _ in range(maxsum + 1)]\nancestors = [[] for _ in range(maxsum + 1)]\n\nprimes = get_primes(maxsum)\n\nfor p in primes:\n    descendants[p].append(p)\n    for s in range(1, len(descendants) - p):\n        descendants[s + p] += [p * pr for pr in descendants[s]]\n\nfor p in primes + [4]:\n    descendants[p].pop()\n\ntotal = 0\nfor s in range(1, maxsum + 1):\n    descendants[s].sort()\n    for d in takewhile(lambda x: x <= maxsum, descendants[s]):\n        ancestors[d] = ancestors[s] + [s]\n    print([s], \"Level:\", len(ancestors[s]))\n    print(\"Ancestors:\", ancestors[s] if len(ancestors[s]) else \"None\")\n    print(\"Descendants:\", len(descendants[s]) if len(descendants[s]) else \"None\")\n    if len(descendants[s]):\n        print(descendants[s])\n    print()\n    total += len(descendants[s])\n\nprint(\"Total descendants\", total)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n"}
{"id": 44427, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 44428, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 44429, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n"}
{"id": 44430, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n"}
{"id": 44431, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n"}
{"id": 44432, "name": "XML_Output", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n"}
{"id": 44433, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 44434, "name": "Plot coordinate pairs", "Python": ">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\n>>> import pylab\n>>> pylab.plot(x, y, 'bo')\n>>> pylab.savefig('qsort-range-10-9.png')\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n"}
{"id": 44435, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n"}
{"id": 44436, "name": "Guess the number_With feedback (player)", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n"}
{"id": 44437, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n"}
{"id": 44438, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 44439, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n"}
{"id": 44440, "name": "Fractal tree", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n"}
{"id": 44441, "name": "Colour pinstripe_Display", "Python": "from turtle import *\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\n\n\nscreen = getscreen()\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nquarter_height = screen.window_height()//4\n\nhalf_height = quarter_height * 2\n\nspeed(\"fastest\")\n\nfor quarter in range(4):\n    pensize(quarter+1)\n    colornum = 0\n\n    min_y = half_height - ((quarter + 1) * quarter_height)\n    max_y = half_height - ((quarter) * quarter_height)\n    \n    for x in range(left_edge,right_edge,quarter+1):\n        penup()\n        pencolor(colors[colornum])\n        colornum = (colornum + 1) % len(colors)\n        setposition(x,min_y)\n        pendown()\n        setposition(x,max_y)\n         \nnotused = input(\"Hit enter to continue: \")\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n"}
{"id": 44442, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 44443, "name": "Doomsday rule", "Python": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n    days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n            \"Friday\", \"Saturday\"]\n    dooms = [\n        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n    ]\n    \n    c = d.year // 100\n    r = d.year % 100\n    s = r // 12\n    t = r % 12\n    c_anchor = (5 * (c % 4) + 2) % 7\n    doomsday = (s + t + (t // 4) + c_anchor) % 7\n    anchorday = dooms[isleap(d.year)][d.month - 1]\n    weekday = (doomsday + d.day - anchorday + 7) % 7\n    return days[weekday]\n\ndates = [date(*x) for x in\n    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n    tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n    print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n"}
{"id": 44444, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Python": "\n            \ndef cocktailshiftingbounds(A):\n    beginIdx = 0\n    endIdx = len(A) - 1\n    \n    while beginIdx <= endIdx:\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        for ii in range(beginIdx,endIdx):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newEndIdx = ii\n                \n        endIdx = newEndIdx\n    \n        for ii in range(endIdx,beginIdx-1,-1):\n            if A[ii] > A[ii + 1]:\n                A[ii+1], A[ii] = A[ii], A[ii+1]\n                newBeginIdx = ii\n        \n        beginIdx = newBeginIdx + 1\n            \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n"}
{"id": 44445, "name": "Animate a pendulum", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n"}
{"id": 44446, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 44447, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 44448, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n"}
{"id": 44449, "name": "Create a file on magnetic tape", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n"}
{"id": 44450, "name": "Create a file on magnetic tape", "Python": ">>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\\n')\n... \n>>>\n", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n"}
{"id": 44451, "name": "Sorting algorithms_Heapsort", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 44452, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n"}
{"id": 44453, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n"}
{"id": 44454, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n"}
{"id": 44455, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n"}
{"id": 44456, "name": "Merge and aggregate datasets", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n"}
{"id": 44457, "name": "Euler method", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 44458, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n"}
{"id": 44459, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n"}
{"id": 44460, "name": "JortSort", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n"}
{"id": 44461, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n"}
{"id": 44462, "name": "Combinations and permutations", "Python": "from __future__ import print_function\n\nfrom scipy.misc import factorial as fact\nfrom scipy.misc import comb\n\ndef perm(N, k, exact=0):\n    return comb(N, k, exact) * fact(k, exact)\n\nexact=True\nprint('Sample Perms 1..12')\nfor N in range(1, 13):\n    k = max(N-2, 1)\n    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\\n')\n          \nprint('\\n\\nSample Combs 10..60')\nfor N in range(10, 61, 10):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\\n')\n\nexact=False\nprint('\\n\\nSample Perms 5..1500 Using FP approximations')\nfor N in [5, 15, 150, 1500, 15000]:\n    k = N-2\n    print('%iP%i =' % (N, k), perm(N, k, exact))\n          \nprint('\\nSample Combs 100..1000 Using FP approximations')\nfor N in range(100, 1001, 100):\n    k = N-2\n    print('%iC%i =' % (N, k), comb(N, k, exact))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n"}
{"id": 44463, "name": "Sort numbers lexicographically", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n"}
{"id": 44464, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n"}
{"id": 44465, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n"}
{"id": 44466, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n"}
{"id": 44467, "name": "Doubly-linked list_Definition", "Python": "from collections import deque\n\nsome_list = deque([\"a\", \"b\", \"c\"])\nprint(some_list)\n\nsome_list.appendleft(\"Z\")\nprint(some_list)\n\nfor value in reversed(some_list):\n    print(value)\n", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n"}
{"id": 44468, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n"}
{"id": 44469, "name": "Permutation test", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n    sumab, suma = sum(ab), sum(a)\n    return ( suma / len(a) -\n             (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n    ab = a + b\n    Tobs = statistic(ab, a)\n    under = 0\n    for count, perm in enumerate(comb(ab, len(a)), 1):\n        if statistic(ab, perm) <= Tobs:\n            under += 1\n    return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n"}
{"id": 44470, "name": "Möbius function", "Python": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\ndef isPrime(n) :\n \n    if (n < 2) :\n        return False\n    for i in range(2, n + 1) :\n        if (i * i <= n and n % i == 0) :\n            return False\n    return True\n \ndef mobius(N) :\n     \n    \n    if (N == 1) :\n        return 1\n \n    \n    \n    \n    p = 0\n    for i in range(1, N + 1) :\n        if (N % i == 0 and\n                isPrime(i)) :\n \n            \n            \n            if (N % (i * i) == 0) :\n                return 0\n            else :\n \n                \n                \n                p = p + 1\n \n    \n    \n    \n    \n    if(p % 2 != 0) :\n        return -1\n    else :\n        return 1\n \n\nprint(\"Mobius numbers from 1..99:\")\n      \nfor i in range(1, 100):\n  print(f\"{mobius(i):>4}\", end = '')\n\n  if i % 20 == 0: print()\n\n\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n"}
{"id": 44471, "name": "Increment a numerical string", "Python": "next = str(int('123') + 1)\n", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n"}
{"id": 44472, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n"}
{"id": 44473, "name": "Sorting algorithms_Permutation sort", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n"}
{"id": 44474, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n"}
{"id": 44475, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 44476, "name": "Abbreviations, simple", "Python": "command_table_text = \n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    input_iter = iter(command_table_text.split())\n\n    word = None\n    try:\n        while True:\n            if word is None:\n                word = next(input_iter)\n            abbr_len = next(input_iter, len(word))\n            try:\n                command_table[word] = int(abbr_len)\n                word = None\n            except ValueError:\n                command_table[word] = len(word)\n                word = abbr_len\n    except StopIteration:\n        pass\n    return command_table\n\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"}
{"id": 44477, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n"}
{"id": 44478, "name": "Tokenize a string with escaping", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n"}
{"id": 44479, "name": "Sexy primes", "Python": "LIMIT = 1_000_035\ndef primes2(limit=LIMIT):\n    if limit < 2: return []\n    if limit < 3: return [2]\n    lmtbf = (limit - 3) // 2\n    buf = [True] * (lmtbf + 1)\n    for i in range((int(limit ** 0.5) - 3) // 2 + 1):\n        if buf[i]:\n            p = i + i + 3\n            s = p * (i + 1) + i\n            buf[s::p] = [False] * ((lmtbf - s) // p + 1)\n    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]\n\nprimes = primes2(LIMIT +6)\nprimeset = set(primes)\nprimearray = [n in primeset for n in range(LIMIT)]\n\n\ns = [[] for x in range(4)]\nunsexy = []\n\nfor p in primes:\n    if p > LIMIT:\n        break\n    if p + 6 in primeset and p + 6 < LIMIT:\n        s[0].append((p, p+6))\n    elif p + 6 in primeset:\n        break\n    else:\n        if p - 6 not in primeset:\n            unsexy.append(p)\n        continue\n    if p + 12 in primeset and p + 12 < LIMIT:\n        s[1].append((p, p+6, p+12))\n    else:\n        continue\n    if p + 18 in primeset and p + 18 < LIMIT:\n        s[2].append((p, p+6, p+12, p+18))\n    else:\n        continue\n    if p + 24 in primeset and p + 24 < LIMIT:\n        s[3].append((p, p+6, p+12, p+18, p+24))\n\n\nprint('\"SEXY\" PRIME GROUPINGS:')\nfor sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):\n    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq\nprintfn \"There are %d unsexy primes less than 1,000,035. The last 10 are:\" n.Length\nArray.skip (n.Length-10) n |> Array.iter(fun n->printf \"%d \" n); printfn \"\"\nlet ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')\n    for sx in sexy[-5:]:\n        print('   ',sx)\n\nprint(f'\\nThere are {len(unsexy)} unsexy primes ending with ...')\nfor usx in unsexy[-10:]:\n    print(' ',usx)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n"}
{"id": 44480, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n"}
{"id": 44481, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 44482, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n"}
{"id": 44483, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n"}
{"id": 44484, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n"}
{"id": 44485, "name": "Singly-linked list_Traversal", "Python": "for node in lst:\n    print node.value\n", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n"}
{"id": 44486, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n"}
{"id": 44487, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n"}
{"id": 44488, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n"}
{"id": 44489, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 44490, "name": "Flipping bits game", "Python": "\n\nfrom random import randrange\nfrom copy import deepcopy\nfrom string import ascii_lowercase\n\n\ntry:    \n    input = raw_input\nexcept:\n    pass\n\nN = 3   \n\nboard  = [[0]* N for i in range(N)]\n\ndef setbits(board, count=1):\n    for i in range(count):\n        board[randrange(N)][randrange(N)] ^= 1\n\ndef shuffle(board, count=1):\n    for i in range(count):\n        if randrange(0, 2):\n            fliprow(randrange(N))\n        else:\n            flipcol(randrange(N))\n\n\ndef pr(board, comment=''):\n    print(str(comment))\n    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))\n    print('  ' + '\\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])\n                             for j, line in enumerate(board, 1)))\n\ndef init(board):\n    setbits(board, count=randrange(N)+1)\n    target = deepcopy(board)\n    while board == target:\n        shuffle(board, count=2 * N)\n    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], \n                                                    ascii_lowercase[N-1])\n    return target, prompt\n\ndef fliprow(i):\n    board[i-1][:] = [x ^ 1 for x in board[i-1] ]\n    \ndef flipcol(i):\n    for row in board:\n        row[i] ^= 1\n\nif __name__ == '__main__':\n    print(__doc__ % (N, N))\n    target, prompt = init(board)\n    pr(target, 'Target configuration is:')\n    print('')\n    turns = 0\n    while board != target:\n        turns += 1\n        pr(board, '%i:' % turns)\n        ans = input(prompt).strip()\n        if (len(ans) == 1 \n            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):\n            flipcol(ascii_lowercase.index(ans))\n        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:\n            fliprow(int(ans))\n        elif ans == 'T':\n            pr(target, 'Target configuration is:')\n            turns -= 1\n        elif ans == 'X':\n            break\n        else:\n            print(\"  I don't understand %r... Try again. \"\n                  \"(X to exit or T to show target)\\n\" % ans[:9])\n            turns -= 1\n    else:\n        print('\\nWell done!\\nBye.')\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n"}
{"id": 44491, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 44492, "name": "Hickerson series of almost integers", "Python": "from decimal import Decimal\nimport math\n\ndef h(n):\n    'Simple, reduced precision calculation'\n    return math.factorial(n) / (2 * math.log(2) ** (n + 1))\n    \ndef h2(n):\n    'Extended precision Hickerson function'\n    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))\n\nfor n in range(18):\n    x = h2(n)\n    norm = str(x.normalize())\n    almostinteger = (' Nearly integer' \n                     if 'E' not in norm and ('.0' in norm or '.9' in norm) \n                     else ' NOT nearly integer!')\n    print('n:%2i h:%s%s' % (n, norm, almostinteger))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n"}
{"id": 44493, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 44494, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 44495, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n"}
{"id": 44496, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n"}
{"id": 44497, "name": "Sorting algorithms_Patience sort", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n"}
{"id": 44498, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 44499, "name": "Bioinformatics_Sequence mutation", "Python": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n    return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n    return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n    for i, part in enumerate(seq_split(dna, n)):\n        print(f\"{i*n:>5}: {part}\")\n    print(\"\\n  BASECOUNT:\")\n    tot = 0\n    for base, count in basecount(dna):\n        print(f\"    {base:>3}: {count}\")\n        tot += count\n    base, count = 'TOT', tot\n    print(f\"    {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n    mutation = []\n    k2txt = dict(I='Insert', D='Delete', S='Substitute')\n    for _ in range(count):\n        kind = random.choice(kinds)\n        index = random.randint(0, len(dna))\n        if kind == 'I':    \n            dna = dna[:index] + random.choice(choice) + dna[index:]\n        elif kind == 'D' and dna:  \n            dna = dna[:index] + dna[index+1:]\n        elif kind == 'S' and dna:  \n            dna = dna[:index] + random.choice(choice) + dna[index+1:]\n        mutation.append((k2txt[kind], index))\n    return dna, mutation\n\nif __name__ == '__main__':\n    length = 250\n    print(\"SEQUENCE:\")\n    sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n    seq_pp(sequence)\n    print(\"\\n\\nMUTATIONS:\")\n    mseq, m = seq_mutate(sequence, 10)\n    for kind, index in m:\n        print(f\" {kind:>10} @{index}\")\n    print()\n    seq_pp(mseq)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n"}
{"id": 44500, "name": "Tau number", "Python": "def tau(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans, i, j = 0, 1, 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans += 1\n            j = n//i\n            if j != i:\n                ans += 1\n        i += 1\n    return ans\n\ndef is_tau_number(n):\n    assert(isinstance(n, int))\n    if n <= 0:\n        return False\n    return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n    n = 1\n    ans = []\n    while len(ans) < 100:\n        if is_tau_number(n):\n            ans.append(n)\n        n += 1\n    print(ans)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n"}
{"id": 44501, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 44502, "name": "Determinant and permanent", "Python": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n    return reduce(mul, lst, 1)\n\ndef perm(a):\n    n = len(a)\n    r = range(n)\n    s = permutations(r)\n    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n    n = len(a)\n    r = range(n)\n    s = spermutations(n)\n    return fsum(sign * prod(a[i][sigma[i]] for i in r)\n                for sigma, sign in s)\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n\n    for a in ( \n            [\n             [1, 2], \n             [3, 4]], \n\n            [\n             [1, 2, 3, 4],\n             [4, 5, 6, 7],\n             [7, 8, 9, 10],\n             [10, 11, 12, 13]],        \n\n            [\n             [ 0,  1,  2,  3,  4],\n             [ 5,  6,  7,  8,  9],\n             [10, 11, 12, 13, 14],\n             [15, 16, 17, 18, 19],\n             [20, 21, 22, 23, 24]],\n        ):\n        print('')\n        pp(a)\n        print('Perm: %s Det: %s' % (perm(a), det(a)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n"}
{"id": 44503, "name": "Partition function P", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n"}
{"id": 44504, "name": "Wireworld", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n"}
{"id": 44505, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 44506, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n"}
{"id": 44507, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 44508, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 44509, "name": "Elliptic curve arithmetic", "Python": "\n\nclass Point:\n    b = 7\n    def __init__(self, x=float('inf'), y=float('inf')):\n        self.x = x\n        self.y = y\n\n    def copy(self):\n        return Point(self.x, self.y)\n\n    def is_zero(self):\n        return self.x > 1e20 or self.x < -1e20\n\n    def neg(self):\n        return Point(self.x, -self.y)\n\n    def dbl(self):\n        if self.is_zero():\n            return self.copy()\n        try:\n            L = (3 * self.x * self.x) / (2 * self.y)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - 2 * self.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def add(self, q):\n        if self.x == q.x and self.y == q.y:\n            return self.dbl()\n        if self.is_zero():\n            return q.copy()\n        if q.is_zero():\n            return self.copy()\n        try:\n            L = (q.y - self.y) / (q.x - self.x)\n        except ZeroDivisionError:\n            return Point()\n        x = L * L - self.x - q.x\n        return Point(x, L * (self.x - x) - self.y)\n\n    def mul(self, n):\n        p = self.copy()\n        r = Point()\n        i = 1\n        while i <= n:\n            if i&n:\n                r = r.add(p)\n            p = p.dbl()\n            i <<= 1\n        return r\n\n    def __str__(self):\n        return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n    print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n    n = y * y - Point.b\n    x = n**(1./3) if n>=0 else -((-n)**(1./3))\n    return Point(x, y)\n\n\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n"}
{"id": 44510, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n"}
{"id": 44511, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 44512, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n"}
{"id": 44513, "name": "String comparison", "Python": "fun compare(a, b):\n    print(\"\\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}\")\n    if a < b: print(\"$a is strictly less than $b\")\n    if a <= b: print(\"$a is less than or equal to $b\")\n    if a >  b: print(\"$a is strictly greater than $b\")\n    if a >= b: print(\"$a is greater than or equal to $b\")\n    if a == b: print(\"$a is equal to $b\")\n    if a != b: print(\"$a is not equal to $b\")\n    if a is b: print(\"$a has object identity with $b\")\n    if a is not b: print(\"$a has negated object identity with $b\")\n\ncompare(\"YUP\", \"YUP\")\ncompare('a', 'z')\ncompare(\"24\", \"123\")\ncompare(24, 123)\ncompare(5.0, 5)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n"}
{"id": 44514, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}
{"id": 44515, "name": "Thiele's interpolation formula", "Python": "\n\nimport math\n\ndef thieleInterpolator(x, y):\n    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]\n    for i in range(len(ρ)-1):\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    for i in range(2, len(ρ)):\n        for j in range(len(ρ)-i):\n            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n    ρ0 = ρ[0]\n    def t(xin):\n        a = 0\n        for i in range(len(ρ0)-1, 1, -1):\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        return y[0] + (xin-x[0]) / (ρ0[1]+a)\n    return t\n\n\nxVal = [i*.05 for i in range(32)]\ntSin = [math.sin(x) for x in xVal]\ntCos = [math.cos(x) for x in xVal]\ntTan = [math.tan(x) for x in xVal]\n\niSin = thieleInterpolator(tSin, xVal)\niCos = thieleInterpolator(tCos, xVal)\niTan = thieleInterpolator(tTan, xVal)\n\nprint('{:16.14f}'.format(6*iSin(.5)))\nprint('{:16.14f}'.format(3*iCos(.5)))\nprint('{:16.14f}'.format(4*iTan(1)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n"}
{"id": 44516, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 44517, "name": "Fibonacci word", "Python": ">>> import math\n>>> from collections import Counter\n>>> \n>>> def entropy(s):\n...     p, lns = Counter(s), float(len(s))\n...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n... \n>>> \n>>> def fibword(nmax=37):\n...     fwords = ['1', '0']\n...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))\n...     def pr(n, fwords):\n...         while len(fwords) < n:\n...             fwords += [''.join(fwords[-2:][::-1])]\n...         v = fwords[n-1]\n...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))\n...     for n in range(1, nmax+1): pr(n, fwords)\n... \n>>> fibword()\nN       Length Entropy    Fibword\n  1          1         -0 1\n  2          1         -0 0\n  3          2          1 01\n  4          3  0.9182958 010\n  5          5  0.9709506 01001\n  6          8   0.954434 01001010\n  7         13  0.9612366 0100101001001\n  8         21  0.9587119 <too long>\n  9         34  0.9596869 <too long>\n 10         55   0.959316 <too long>\n 11         89  0.9594579 <too long>\n 12        144  0.9594038 <too long>\n 13        233  0.9594244 <too long>\n 14        377  0.9594165 <too long>\n 15        610  0.9594196 <too long>\n 16        987  0.9594184 <too long>\n 17       1597  0.9594188 <too long>\n 18       2584  0.9594187 <too long>\n 19       4181  0.9594187 <too long>\n 20       6765  0.9594187 <too long>\n 21      10946  0.9594187 <too long>\n 22      17711  0.9594187 <too long>\n 23      28657  0.9594187 <too long>\n 24      46368  0.9594187 <too long>\n 25      75025  0.9594187 <too long>\n 26     121393  0.9594187 <too long>\n 27     196418  0.9594187 <too long>\n 28     317811  0.9594187 <too long>\n 29     514229  0.9594187 <too long>\n 30     832040  0.9594187 <too long>\n 31    1346269  0.9594187 <too long>\n 32    2178309  0.9594187 <too long>\n 33    3524578  0.9594187 <too long>\n 34    5702887  0.9594187 <too long>\n 35    9227465  0.9594187 <too long>\n 36   14930352  0.9594187 <too long>\n 37   24157817  0.9594187 <too long>\n>>>\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n"}
{"id": 44518, "name": "Angles (geometric), normalization and conversion", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n"}
{"id": 44519, "name": "Find common directory path", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n"}
{"id": 44520, "name": "Verify distribution uniformity_Naive", "Python": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n    \n    bin = Counter(fn() for i in range(repeats))\n    target = repeats // len(bin)\n    deltacount = int(delta / 100. * target)\n    assert all( abs(target - count) < deltacount\n                for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n                    target, deltacount, [ (key, target - count)\n                                          for key, count in sorted(bin.items()) ]\n                    )\n    pp(dict(bin))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 44521, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 44522, "name": "Stirling numbers of the second kind", "Python": "computed = {}\n\ndef sterling2(n, k):\n\tkey = str(n) + \",\" + str(k)\n\n\tif key in computed.keys():\n\t\treturn computed[key]\n\tif n == k == 0:\n\t\treturn 1\n\tif (n > 0 and k == 0) or (n == 0 and k > 0):\n\t\treturn 0\n\tif n == k:\n\t\treturn 1\n\tif k > n:\n\t\treturn 0\n\tresult = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n\tcomputed[key] = result\n\treturn result\n\nprint(\"Stirling numbers of the second kind:\")\nMAX = 12\nprint(\"n/k\".ljust(10), end=\"\")\nfor n in range(MAX + 1):\n\tprint(str(n).rjust(10), end=\"\")\nprint()\nfor n in range(MAX + 1):\n\tprint(str(n).ljust(10), end=\"\")\n\tfor k in range(n + 1):\n\t\tprint(str(sterling2(n, k)).rjust(10), end=\"\")\n\tprint()\nprint(\"The maximum value of S2(100, k) = \")\nprevious = 0\nfor k in range(1, 100 + 1):\n\tcurrent = sterling2(100, k)\n\tif current > previous:\n\t\tprevious = current\n\telse:\n\t\tprint(\"{0}\\n({1} digits, k = {2})\\n\".format(previous, len(str(previous)), k - 1))\n\t\tbreak\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n"}
{"id": 44523, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 44524, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n"}
{"id": 44525, "name": "Memory allocation", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n"}
{"id": 44526, "name": "Tic-tac-toe", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n"}
{"id": 44527, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 44528, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n"}
{"id": 44529, "name": "Entropy_Narcissist", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n"}
{"id": 44530, "name": "Entropy_Narcissist", "Python": "import math\nfrom collections import Counter\n\ndef entropy(s):\n    p, lns = Counter(s), float(len(s))\n    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n    b=f.read()\n    \nprint(entropy(b))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n"}
{"id": 44531, "name": "DNS query", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 44532, "name": "DNS query", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 44533, "name": "Peano curve", "Python": "import turtle as tt\nimport inspect\n\nstack = [] \ndef peano(iterations=1):\n    global stack\n\n    \n    ivan = tt.Turtle(shape = \"classic\", visible = True)\n\n\n    \n    screen = tt.Screen()\n    screen.title(\"Desenhin do Peano\")\n    screen.bgcolor(\"\n    screen.delay(0) \n    screen.setup(width=0.95, height=0.9)\n\n    \n    walk = 1\n\n    def screenlength(k):\n        \n        \n        if k != 0:\n            length = screenlength(k-1)\n            return 2*length + 1\n        else: return 0\n\n    kkkj = screenlength(iterations)\n    screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)\n    ivan.color(\"\n\n\n    \n    def step1(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n    def step2(k):\n        global stack\n        stack.append(len(inspect.stack()))\n        if k != 0:\n            ivan.right(90)\n            step1(k - 1)\n            ivan.forward(walk)\n            ivan.left(90)\n            step2(k - 1)\n            ivan.forward(walk)\n            step2(k - 1)\n            ivan.left(90)\n            ivan.forward(walk)\n            step1(k - 1)\n            ivan.right(90)\n\n    \n    ivan.left(90)\n    step2(iterations)\n\n    tt.done()\n\nif __name__ == \"__main__\":\n    peano(4)\n    import pylab as P \n    P.plot(stack)\n    P.show()\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar points []gg.Point\n\nconst width = 81\n\nfunc peano(x, y, lg, i1, i2 int) {\n    if lg == 1 {\n        px := float64(width-x) * 10\n        py := float64(width-y) * 10\n        points = append(points, gg.Point{px, py})\n        return\n    }\n    lg /= 3\n    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)\n    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)\n    peano(x+lg, y+lg, lg, i1, 1-i2)\n    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)\n    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)\n    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)\n    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)\n    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)\n    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)\n}\n\nfunc main() {\n    peano(0, 0, width, 0, 0)\n    dc := gg.NewContext(820, 820)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for _, p := range points {\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetRGB(1, 0, 1) \n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"peano.png\")\n}\n"}
{"id": 44534, "name": "Seven-sided dice from five-sided dice", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 44535, "name": "Seven-sided dice from five-sided dice", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n"}
{"id": 44536, "name": "Solve the no connection puzzle", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n"}
{"id": 44537, "name": "Solve the no connection puzzle", "Python": "from __future__ import print_function\nfrom itertools import permutations\nfrom enum import Enum\n\nA, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')\n\nconnections = ((A, C), (A, D), (A, E),\n               (B, D), (B, E), (B, F),\n               (G, C), (G, D), (G, E),\n               (H, D), (H, E), (H, F),\n               (C, D), (D, E), (E, F))\n\n\ndef ok(conn, perm):\n    \n    this, that = (c.value - 1 for c in conn)\n    return abs(perm[this] - perm[that]) != 1\n\n\ndef solve():\n    return [perm for perm in permutations(range(1, 9))\n            if all(ok(conn, perm) for conn in connections)]\n\n\nif __name__ == '__main__':\n    solutions = solve()\n    print(\"A, B, C, D, E, F, G, H =\", ', '.join(str(i) for i in solutions[0]))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n"}
{"id": 44538, "name": "Extensible prime generator", "Python": "islice(count(7), 0, None, 2)\n", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"fmt\"\n)\n\nfunc main() {\n    p := newP()\n    fmt.Print(\"First twenty: \")\n    for i := 0; i < 20; i++ {\n        fmt.Print(p(), \" \")\n    }\n    fmt.Print(\"\\nBetween 100 and 150: \")\n    n := p()\n    for n <= 100 {\n        n = p()\n    }\n    for ; n < 150; n = p() {\n        fmt.Print(n, \" \")\n    }\n    for n <= 7700 {\n        n = p()\n    }\n    c := 0\n    for ; n < 8000; n = p() {\n        c++\n    }\n    fmt.Println(\"\\nNumber beween 7,700 and 8,000:\", c)\n    p = newP()\n    for i := 1; i < 10000; i++ {\n        p()\n    }\n    fmt.Println(\"10,000th prime:\", p())\n}\n\nfunc newP() func() int {\n    n := 1\n    var pq pQueue\n    top := &pMult{2, 4, 0}\n    return func() int {\n        for {\n            n++\n            if n < top.pMult { \n                heap.Push(&pq, &pMult{prime: n, pMult: n * n})\n                top = pq[0]\n                return n\n            }\n            \n            for top.pMult == n {\n                top.pMult += top.prime\n                heap.Fix(&pq, 0)\n                top = pq[0]\n            }\n        }\n    }\n}\n\ntype pMult struct {\n    prime int\n    pMult int\n    index int\n}\n\ntype pQueue []*pMult\n\nfunc (q pQueue) Len() int           { return len(q) }\nfunc (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }\nfunc (q pQueue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n    q[i].index = i\n    q[j].index = j\n}\nfunc (p *pQueue) Push(x interface{}) {\n    q := *p\n    e := x.(*pMult)\n    e.index = len(q)\n    *p = append(q, e)\n}\nfunc (p *pQueue) Pop() interface{} {\n    q := *p\n    last := len(q) - 1\n    e := q[last]\n    *p = q[:last]\n    return e\n}\n"}
{"id": 44539, "name": "Rock-paper-scissors", "Python": "from random import choice\n\nrules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}\nprevious = ['rock', 'paper', 'scissors']\n\nwhile True:\n    human = input('\\nchoose your weapon: ')\n    computer = rules[choice(previous)]  \n\n    if human in ('quit', 'exit'): break\n\n    elif human in rules:\n        previous.append(human)\n        print('the computer played', computer, end='; ')\n\n        if rules[computer] == human:  \n            print('yay you win!')\n        elif rules[human] == computer:  \n            print('the computer beat you... :(')\n        else: print(\"it's a tie!\")\n\n    else: print(\"that's not a valid choice\")\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n"}
{"id": 44540, "name": "Create a two-dimensional array at runtime", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n"}
{"id": 44541, "name": "Chinese remainder theorem", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 44542, "name": "Chinese remainder theorem", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n"}
{"id": 44543, "name": "Vigenère cipher_Cryptanalysis", "Python": "from string import uppercase\nfrom operator import itemgetter\n\ndef vigenere_decrypt(target_freqs, input):\n    nchars = len(uppercase)\n    ordA = ord('A')\n    sorted_targets = sorted(target_freqs)\n\n    def frequency(input):\n        result = [[c, 0.0] for c in uppercase]\n        for c in input:\n            result[c - ordA][1] += 1\n        return result\n\n    def correlation(input):\n        result = 0.0\n        freq = frequency(input)\n        freq.sort(key=itemgetter(1))\n\n        for i, f in enumerate(freq):\n            result += f[1] * sorted_targets[i]\n        return result\n\n    cleaned = [ord(c) for c in input.upper() if c.isupper()]\n    best_len = 0\n    best_corr = -100.0\n\n    \n    \n    for i in xrange(2, len(cleaned) // 20):\n        pieces = [[] for _ in xrange(i)]\n        for j, c in enumerate(cleaned):\n            pieces[j % i].append(c)\n\n        \n        \n        corr = -0.5 * i + sum(correlation(p) for p in pieces)\n\n        if corr > best_corr:\n            best_len = i\n            best_corr = corr\n\n    if best_len == 0:\n        return (\"Text is too short to analyze\", \"\")\n\n    pieces = [[] for _ in xrange(best_len)]\n    for i, c in enumerate(cleaned):\n        pieces[i % best_len].append(c)\n\n    freqs = [frequency(p) for p in pieces]\n\n    key = \"\"\n    for fr in freqs:\n        fr.sort(key=itemgetter(1), reverse=True)\n\n        m = 0\n        max_corr = 0.0\n        for j in xrange(nchars):\n            corr = 0.0\n            c = ordA + j\n            for frc in fr:\n                d = (ord(frc[0]) - c + nchars) % nchars\n                corr += frc[1] * target_freqs[d]\n\n            if corr > max_corr:\n                m = j\n                max_corr = corr\n\n        key += chr(m + ordA)\n\n    r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)\n         for i, c in enumerate(cleaned))\n    return (key, \"\".join(r))\n\n\ndef main():\n    encoded = \n\n    english_frequences = [\n        0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n        0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n        0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n        0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\n    (key, decoded) = vigenere_decrypt(english_frequences, encoded)\n    print \"Key:\", key\n    print \"\\nText:\", decoded\n\nmain()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar encoded = \n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [26]float64{\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n}\n\nfunc sum(a []float64) (sum float64) {\n    for _, f := range a {\n        sum += f\n    }\n    return\n}\n\nfunc bestMatch(a []float64) int {\n    sum := sum(a)\n    bestFit, bestRotate := 1e100, 0\n    for rotate := 0; rotate < 26; rotate++ {\n        fit := 0.0\n        for i := 0; i < 26; i++ {\n            d := a[(i+rotate)%26]/sum - freq[i]\n            fit += d * d / freq[i]\n        }\n        if fit < bestFit {\n            bestFit, bestRotate = fit, rotate\n        }\n    }\n    return bestRotate\n}\n\nfunc freqEveryNth(msg []int, key []byte) float64 {\n    l := len(msg)\n    interval := len(key)\n    out := make([]float64, 26)\n    accu := make([]float64, 26)\n    for j := 0; j < interval; j++ {\n        for k := 0; k < 26; k++ {\n            out[k] = 0.0\n        }\n        for i := j; i < l; i += interval {\n            out[msg[i]]++\n        }\n        rot := bestMatch(out)\n        key[j] = byte(rot + 65)\n        for i := 0; i < 26; i++ {\n            accu[i] += out[(i+rot)%26]\n        }\n    }\n    sum := sum(accu)\n    ret := 0.0\n    for i := 0; i < 26; i++ {\n        d := accu[i]/sum - freq[i]\n        ret += d * d / freq[i]\n    }\n    return ret\n}\n\nfunc decrypt(text, key string) string {\n    var sb strings.Builder\n    ki := 0\n    for _, c := range text {\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        ci := (c - rune(key[ki]) + 26) % 26\n        sb.WriteRune(ci + 65)\n        ki = (ki + 1) % len(key)\n    }\n    return sb.String()\n}\n\nfunc main() {\n    enc := strings.Replace(encoded, \" \", \"\", -1)\n    txt := make([]int, len(enc))\n    for i := 0; i < len(txt); i++ {\n        txt[i] = int(enc[i] - 'A')\n    }\n    bestFit, bestKey := 1e100, \"\"\n    fmt.Println(\"  Fit     Length   Key\")\n    for j := 1; j <= 26; j++ {\n        key := make([]byte, j)\n        fit := freqEveryNth(txt, key)\n        sKey := string(key)\n        fmt.Printf(\"%f    %2d     %s\", fit, j, sKey)\n        if fit < bestFit {\n            bestFit, bestKey = fit, sKey\n            fmt.Print(\" <--- best so far\")\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nBest key :\", bestKey)\n    fmt.Printf(\"\\nDecrypted text:\\n%s\\n\", decrypt(enc, bestKey))\n}\n"}
{"id": 44544, "name": "Pi", "Python": "def calcPi():\n    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n    while True:\n        if 4*q+r-t < n*t:\n            yield n\n            nr = 10*(r-n*t)\n            n  = ((10*(3*q+r))//t)-10*n\n            q  *= 10\n            r  = nr\n        else:\n            nr = (2*q+r)*l\n            nn = (q*(7*k)+2+(r*l))//(t*l)\n            q  *= k\n            t  *= l\n            l  += 2\n            k += 1\n            n  = nn\n            r  = nr\n\nimport sys\npi_digits = calcPi()\ni = 0\nfor d in pi_digits:\n    sys.stdout.write(str(d))\n    i += 1\n    if i == 40: print(\"\"); i = 0\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n"}
{"id": 44545, "name": "Hofstadter Q sequence", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n"}
{"id": 44546, "name": "Hofstadter Q sequence", "Python": "def q(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return q.seq[n]\n    except IndexError:\n        ans = q(n - q(n - 1)) + q(n - q(n - 2))\n        q.seq.append(ans)\n        return ans\nq.seq = [None, 1, 1]\n\nif __name__ == '__main__':\n    first10 = [q(i) for i in range(1,11)]\n    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], \"Q() value error(s)\"\n    print(\"Q(n) for n = [1..10] is:\", ', '.join(str(i) for i in first10))\n    assert q(1000) == 502, \"Q(1000) value error\"\n    print(\"Q(1000) =\", q(1000))\n", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n"}
{"id": 44547, "name": "Y combinator", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))\n>>> [ Y(fac)(i) for i in range(10) ]\n[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]\n>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))\n>>> [ Y(fib)(i) for i in range(10) ]\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n"}
{"id": 44548, "name": "Return multiple values", "Python": "def addsub(x, y):\n  return x + y, x - y\n", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n"}
{"id": 44549, "name": "Van Eck sequence", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 44550, "name": "Van Eck sequence", "Python": "def van_eck():\n    n, seen, val = 0, {}, 0\n    while True:\n        yield val\n        last = {val: n}\n        val = n - seen.get(val, n)\n        seen.update(last)\n        n += 1\n\nif __name__ == '__main__':\n    print(\"Van Eck: first 10 terms:  \", list(islice(van_eck(), 10)))\n    print(\"Van Eck: terms 991 - 1000:\", list(islice(van_eck(), 1000))[-10:])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n"}
{"id": 44551, "name": "FTP", "Python": "from ftplib import FTP\nftp = FTP('kernel.org')\nftp.login()\nftp.cwd('/pub/linux/kernel')\nftp.set_pasv(True) \nprint ftp.retrlines('LIST')\nprint ftp.retrbinary('RETR README', open('README', 'wb').write)\nftp.quit()\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n"}
{"id": 44552, "name": "24 game", "Python": "\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n\ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            print (\"New digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n\nif __name__ == '__main__': main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n"}
{"id": 44553, "name": "24 game", "Python": "\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n\ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            print (\"New digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n\nif __name__ == '__main__': main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n"}
{"id": 44554, "name": "24 game", "Python": "\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n\ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            print (\"New digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n\nif __name__ == '__main__': main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n"}
{"id": 44555, "name": "Loops_Continue", "Python": "for i in range(1, 11):\n    if i % 5 == 0:\n        print(i)\n        continue\n    print(i, end=', ')\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 10; i++ {\n        fmt.Printf(\"%d\", i)\n        if i%5 == 0 {\n            fmt.Printf(\"\\n\")\n            continue\n        }\n        fmt.Printf(\", \")\n    }\n}\n"}
{"id": 44556, "name": "Colour bars_Display", "Python": "\n\n\nfrom livewires import *\n\nhoriz=640; vert=480\nbegin_graphics(width=horiz,height=vert,title=\"v_stripes\",background=Colour.black)\nNameColors=[\"black\",\"red\",\"green\",\"dark_blue\",\"purple\",\"blue\",\"yellow\",\"white\"]\nstepik=horiz/len(NameColors)\n\nfor index,each in enumerate(NameColors):\n\tExcStrng=\"set_colour(Colour.\"+each+\")\"\n\texec ExcStrng\n\tbox(index*stepik,0,(index+1)*stepik,vert,filled=1)\n\nwhile keys_pressed() != ['x']: \n\tpass\n\nend_graphics()\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 44557, "name": "Colour bars_Display", "Python": "\n\n\nfrom livewires import *\n\nhoriz=640; vert=480\nbegin_graphics(width=horiz,height=vert,title=\"v_stripes\",background=Colour.black)\nNameColors=[\"black\",\"red\",\"green\",\"dark_blue\",\"purple\",\"blue\",\"yellow\",\"white\"]\nstepik=horiz/len(NameColors)\n\nfor index,each in enumerate(NameColors):\n\tExcStrng=\"set_colour(Colour.\"+each+\")\"\n\texec ExcStrng\n\tbox(index*stepik,0,(index+1)*stepik,vert,filled=1)\n\nwhile keys_pressed() != ['x']: \n\tpass\n\nend_graphics()\n", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n"}
{"id": 44558, "name": "LU decomposition", "Python": "from pprint import pprint\n\ndef matrixMul(A, B):\n    TB = zip(*B)\n    return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]\n\ndef pivotize(m):\n    \n    n = len(m)\n    ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]\n    for j in xrange(n):\n        row = max(xrange(j, n), key=lambda i: abs(m[i][j]))\n        if j != row:\n            ID[j], ID[row] = ID[row], ID[j]\n    return ID\n\ndef lu(A):\n    \n    n = len(A)\n    L = [[0.0] * n for i in xrange(n)]\n    U = [[0.0] * n for i in xrange(n)]\n    P = pivotize(A)\n    A2 = matrixMul(P, A)\n    for j in xrange(n):\n        L[j][j] = 1.0\n        for i in xrange(j+1):\n            s1 = sum(U[k][j] * L[i][k] for k in xrange(i))\n            U[i][j] = A2[i][j] - s1\n        for i in xrange(j, n):\n            s2 = sum(U[k][j] * L[i][k] for k in xrange(j))\n            L[i][j] = (A2[i][j] - s2) / U[j][j]\n    return (L, U, P)\n\na = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]\nfor part in lu(a):\n    pprint(part, width=19)\n    print\nprint\nb = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]\nfor part in lu(b):\n    pprint(part)\n    print\n", "Go": "package main\n\nimport \"fmt\"\n    \ntype matrix [][]float64\n\nfunc zero(n int) matrix {\n    r := make([][]float64, n)\n    a := make([]float64, n*n)\n    for i := range r {\n        r[i] = a[n*i : n*(i+1)]\n    } \n    return r \n}\n    \nfunc eye(n int) matrix {\n    r := zero(n)\n    for i := range r {\n        r[i][i] = 1\n    }\n    return r\n}   \n    \nfunc (m matrix) print(label string) {\n    if label > \"\" {\n        fmt.Printf(\"%s:\\n\", label)\n    }\n    for _, r := range m {\n        for _, e := range r {\n            fmt.Printf(\" %9.5f\", e)\n        }\n        fmt.Println()\n    }\n}\n\nfunc (a matrix) pivotize() matrix { \n    p := eye(len(a))\n    for j, r := range a {\n        max := r[j] \n        row := j\n        for i := j; i < len(a); i++ {\n            if a[i][j] > max {\n                max = a[i][j]\n                row = i\n            }\n        }\n        if j != row {\n            \n            p[j], p[row] = p[row], p[j]\n        }\n    } \n    return p\n}\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    r := zero(len(m1))\n    for i, r1 := range m1 {\n        for j := range m2 {\n            for k := range m1 {\n                r[i][j] += r1[k] * m2[k][j]\n            }\n        }\n    }\n    return r\n}\n\nfunc (a matrix) lu() (l, u, p matrix) {\n    l = zero(len(a))\n    u = zero(len(a))\n    p = a.pivotize()\n    a = p.mul(a)\n    for j := range a {\n        l[j][j] = 1\n        for i := 0; i <= j; i++ {\n            sum := 0.\n            for k := 0; k < i; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            u[i][j] = a[i][j] - sum\n        }\n        for i := j; i < len(a); i++ {\n            sum := 0.\n            for k := 0; k < j; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            l[i][j] = (a[i][j] - sum) / u[j][j]\n        }\n    }\n    return\n}\n\nfunc main() {\n    showLU(matrix{\n        {1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}})\n    showLU(matrix{\n        {11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}})\n}\n\nfunc showLU(a matrix) {\n    a.print(\"\\na\")\n    l, u, p := a.lu()\n    l.print(\"l\")\n    u.print(\"u\") \n    p.print(\"p\") \n}\n"}
{"id": 44559, "name": "General FizzBuzz", "Python": "def genfizzbuzz(factorwords, numbers):\n    \n    factorwords.sort(key=lambda factor_and_word: factor_and_word[0])\n    lines = []\n    for num in numbers:\n        words = ''.join(word for factor, word in factorwords if (num % factor) == 0)\n        lines.append(words if words else str(num))\n    return '\\n'.join(lines)\n\nif __name__ == '__main__':\n    print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n)\n\nconst numbers = 3\n\nfunc main() {\n\n\t\n\tmax := 20\n\twords := map[int]string{\n\t\t3: \"Fizz\",\n\t\t5: \"Buzz\",\n\t\t7: \"Baxx\",\n\t}\n\tkeys := []int{3, 5, 7}\n\tdivisible := false\n\tfor i := 1; i <= max; i++ {\n\t\tfor _, n := range keys {\n\t\t\tif i % n == 0 {\n\t\t\t\tfmt.Print(words[n])\n\t\t\t\tdivisible = true\n\t\t\t}\n\t\t}\n\t\tif !divisible {\n\t\t\tfmt.Print(i)\n\t\t}\n\t\tfmt.Println()\n\t\tdivisible = false\n\t}\n\n}\n"}
{"id": 44560, "name": "Read a specific line from a file", "Python": "with open('xxx.txt') as f:\n    for i, line in enumerate(f):\n        if i == 6:\n            break\n    else:\n        print('Not 7 lines in file')\n        line = None\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif line, err := rsl(\"input.txt\", 7); err == nil {\n\t\tfmt.Println(\"7th line:\")\n\t\tfmt.Println(line)\n\t} else {\n\t\tfmt.Println(\"rsl:\", err)\n\t}\n}\n\nfunc rsl(fn string, n int) (string, error) {\n\tif n < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid request: line %d\", n)\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tbf := bufio.NewReader(f)\n\tvar line string\n\tfor lnum := 0; lnum < n; lnum++ {\n\t\tline, err = bf.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tswitch lnum {\n\t\t\tcase 0:\n\t\t\t\treturn \"\", errors.New(\"no lines in file\")\n\t\t\tcase 1:\n\t\t\t\treturn \"\", errors.New(\"only 1 line\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"only %d lines\", lnum)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif line == \"\" {\n\t\treturn \"\", fmt.Errorf(\"line %d empty\", n)\n\t}\n\treturn line, nil\n}\n"}
{"id": 44561, "name": "Read a specific line from a file", "Python": "with open('xxx.txt') as f:\n    for i, line in enumerate(f):\n        if i == 6:\n            break\n    else:\n        print('Not 7 lines in file')\n        line = None\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif line, err := rsl(\"input.txt\", 7); err == nil {\n\t\tfmt.Println(\"7th line:\")\n\t\tfmt.Println(line)\n\t} else {\n\t\tfmt.Println(\"rsl:\", err)\n\t}\n}\n\nfunc rsl(fn string, n int) (string, error) {\n\tif n < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid request: line %d\", n)\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tbf := bufio.NewReader(f)\n\tvar line string\n\tfor lnum := 0; lnum < n; lnum++ {\n\t\tline, err = bf.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tswitch lnum {\n\t\t\tcase 0:\n\t\t\t\treturn \"\", errors.New(\"no lines in file\")\n\t\t\tcase 1:\n\t\t\t\treturn \"\", errors.New(\"only 1 line\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"only %d lines\", lnum)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif line == \"\" {\n\t\treturn \"\", fmt.Errorf(\"line %d empty\", n)\n\t}\n\treturn line, nil\n}\n"}
{"id": 44562, "name": "Read a specific line from a file", "Python": "with open('xxx.txt') as f:\n    for i, line in enumerate(f):\n        if i == 6:\n            break\n    else:\n        print('Not 7 lines in file')\n        line = None\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif line, err := rsl(\"input.txt\", 7); err == nil {\n\t\tfmt.Println(\"7th line:\")\n\t\tfmt.Println(line)\n\t} else {\n\t\tfmt.Println(\"rsl:\", err)\n\t}\n}\n\nfunc rsl(fn string, n int) (string, error) {\n\tif n < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid request: line %d\", n)\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tbf := bufio.NewReader(f)\n\tvar line string\n\tfor lnum := 0; lnum < n; lnum++ {\n\t\tline, err = bf.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tswitch lnum {\n\t\t\tcase 0:\n\t\t\t\treturn \"\", errors.New(\"no lines in file\")\n\t\t\tcase 1:\n\t\t\t\treturn \"\", errors.New(\"only 1 line\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"only %d lines\", lnum)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif line == \"\" {\n\t\treturn \"\", fmt.Errorf(\"line %d empty\", n)\n\t}\n\treturn line, nil\n}\n"}
{"id": 44563, "name": "File extension is in extensions list", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar extensions = []string{\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\n\nfunc fileExtInList(filename string) (bool, string) {\n    filename2 := strings.ToLower(filename)\n    for _, ext := range extensions {\n        ext2 := \".\" + strings.ToLower(ext)\n        if strings.HasSuffix(filename2, ext2) {\n            return true, ext\n        }\n    }\n    s := strings.Split(filename, \".\")\n    if len(s) > 1 {\n        t := s[len(s)-1]\n        if t != \"\" {\n            return false, t\n        } else {\n            return false, \"<empty>\"\n        }\n    } else {\n        return false, \"<none>\"\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The listed extensions are:\")\n    fmt.Println(extensions, \"\\n\")\n    tests := []string{\n        \"MyData.a##\", \"MyData.tar.Gz\", \"MyData.gzip\",\n        \"MyData.7z.backup\", \"MyData...\", \"MyData\",\n        \"MyData_v1.0.tar.bz2\", \"MyData_v1.0.bz2\",\n    }\n    for _, test := range tests {\n        ok, ext := fileExtInList(test)\n        fmt.Printf(\"%-20s => %-5t  (extension = %s)\\n\", test, ok, ext)\n    }\n}\n"}
{"id": 44564, "name": "File extension is in extensions list", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar extensions = []string{\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\n\nfunc fileExtInList(filename string) (bool, string) {\n    filename2 := strings.ToLower(filename)\n    for _, ext := range extensions {\n        ext2 := \".\" + strings.ToLower(ext)\n        if strings.HasSuffix(filename2, ext2) {\n            return true, ext\n        }\n    }\n    s := strings.Split(filename, \".\")\n    if len(s) > 1 {\n        t := s[len(s)-1]\n        if t != \"\" {\n            return false, t\n        } else {\n            return false, \"<empty>\"\n        }\n    } else {\n        return false, \"<none>\"\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The listed extensions are:\")\n    fmt.Println(extensions, \"\\n\")\n    tests := []string{\n        \"MyData.a##\", \"MyData.tar.Gz\", \"MyData.gzip\",\n        \"MyData.7z.backup\", \"MyData...\", \"MyData\",\n        \"MyData_v1.0.tar.bz2\", \"MyData_v1.0.bz2\",\n    }\n    for _, test := range tests {\n        ok, ext := fileExtInList(test)\n        fmt.Printf(\"%-20s => %-5t  (extension = %s)\\n\", test, ok, ext)\n    }\n}\n"}
{"id": 44565, "name": "File extension is in extensions list", "Python": "def isExt(fileName, extensions):\n  return True in map(fileName.lower().endswith, (\".\" + e.lower() for e in extensions))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar extensions = []string{\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\n\nfunc fileExtInList(filename string) (bool, string) {\n    filename2 := strings.ToLower(filename)\n    for _, ext := range extensions {\n        ext2 := \".\" + strings.ToLower(ext)\n        if strings.HasSuffix(filename2, ext2) {\n            return true, ext\n        }\n    }\n    s := strings.Split(filename, \".\")\n    if len(s) > 1 {\n        t := s[len(s)-1]\n        if t != \"\" {\n            return false, t\n        } else {\n            return false, \"<empty>\"\n        }\n    } else {\n        return false, \"<none>\"\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The listed extensions are:\")\n    fmt.Println(extensions, \"\\n\")\n    tests := []string{\n        \"MyData.a##\", \"MyData.tar.Gz\", \"MyData.gzip\",\n        \"MyData.7z.backup\", \"MyData...\", \"MyData\",\n        \"MyData_v1.0.tar.bz2\", \"MyData_v1.0.bz2\",\n    }\n    for _, test := range tests {\n        ok, ext := fileExtInList(test)\n        fmt.Printf(\"%-20s => %-5t  (extension = %s)\\n\", test, ok, ext)\n    }\n}\n"}
{"id": 44566, "name": "24 game_Solve", "Python": "\n \nfrom   __future__ import division, print_function\nfrom   itertools  import permutations, combinations, product, \\\n                         chain\nfrom   pprint     import pprint as pp\nfrom   fractions  import Fraction as F\nimport random, ast, re\nimport sys\n \nif sys.version_info[0] < 3:\n    input = raw_input\n    from itertools import izip_longest as zip_longest\nelse:\n    from itertools import zip_longest\n \n \ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n \ndef ask4():\n    'get four random digits >0 from the player'\n    digits = ''\n    while len(digits) != 4 or not all(d in '123456789' for d in digits):\n        digits = input('Enter the digits to solve for: ')\n        digits = ''.join(digits.strip().split())\n    return list(digits)\n \ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n \ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n \ndef solve(digits):\n    \n    digilen = len(digits)\n    \n    exprlen = 2 * digilen - 1\n    \n    digiperm = sorted(set(permutations(digits)))\n    \n    opcomb   = list(product('+-*/', repeat=digilen-1))\n    \n    brackets = ( [()] + [(x,y)\n                         for x in range(0, exprlen, 2)\n                         for y in range(x+4, exprlen+2, 2)\n                         if (x,y) != (0,exprlen+1)]\n                 + [(0, 3+1, 4+2, 7+3)] ) \n    for d in digiperm:\n        for ops in opcomb:\n            if '/' in ops:\n                d2 = [('F(%s)' % i) for i in d] \n            else:\n                d2 = d\n            ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))\n            for b in brackets:\n                exp = ex[::]\n                for insertpoint, bracket in zip(b, '()'*(len(b)//2)):\n                    exp.insert(insertpoint, bracket)\n                txt = ''.join(exp)\n                try:\n                    num = eval(txt)\n                except ZeroDivisionError:\n                    continue\n                if num == 24:\n                    if '/' in ops:\n                        exp = [ (term if not term.startswith('F(') else term[2])\n                               for term in exp ]\n                    ans = ' '.join(exp).rstrip()\n                    print (\"Solution found:\",ans)\n                    return ans\n    print (\"No solution found for:\", ' '.join(digits))            \n    return '!'\n \ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer == '?':\n            solve(digits)\n            answer = '!'\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if answer == '!!':\n            digits = ask4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            if '/' in answer:\n                \n                answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)\n                                  for char in answer )\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n \nmain()\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nconst (\n\top_num = iota\n\top_add\n\top_sub\n\top_mul\n\top_div\n)\n\ntype frac struct {\n\tnum, denom int\n}\n\n\n\ntype Expr struct {\n\top          int\n\tleft, right *Expr\n\tvalue       frac\n}\n\nvar n_cards = 4\nvar goal = 24\nvar digit_range = 9\n\nfunc (x *Expr) String() string {\n\tif x.op == op_num {\n\t\treturn fmt.Sprintf(\"%d\", x.value.num)\n\t}\n\n\tvar bl1, br1, bl2, br2, opstr string\n\tswitch {\n\tcase x.left.op == op_num:\n\tcase x.left.op >= x.op:\n\tcase x.left.op == op_add && x.op == op_sub:\n\t\tbl1, br1 = \"\", \"\"\n\tdefault:\n\t\tbl1, br1 = \"(\", \")\"\n\t}\n\n\tif x.right.op == op_num || x.op < x.right.op {\n\t\tbl2, br2 = \"\", \"\"\n\t} else {\n\t\tbl2, br2 = \"(\", \")\"\n\t}\n\n\tswitch {\n\tcase x.op == op_add:\n\t\topstr = \" + \"\n\tcase x.op == op_sub:\n\t\topstr = \" - \"\n\tcase x.op == op_mul:\n\t\topstr = \" * \"\n\tcase x.op == op_div:\n\t\topstr = \" / \"\n\t}\n\n\treturn bl1 + x.left.String() + br1 + opstr +\n\t\tbl2 + x.right.String() + br2\n}\n\nfunc expr_eval(x *Expr) (f frac) {\n\tif x.op == op_num {\n\t\treturn x.value\n\t}\n\n\tl, r := expr_eval(x.left), expr_eval(x.right)\n\n\tswitch x.op {\n\tcase op_add:\n\t\tf.num = l.num*r.denom + l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_sub:\n\t\tf.num = l.num*r.denom - l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_mul:\n\t\tf.num = l.num * r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_div:\n\t\tf.num = l.num * r.denom\n\t\tf.denom = l.denom * r.num\n\t\treturn\n\t}\n\treturn\n}\n\nfunc solve(ex_in []*Expr) bool {\n\t\n\t\n\tif len(ex_in) == 1 {\n\t\tf := expr_eval(ex_in[0])\n\t\tif f.denom != 0 && f.num == f.denom*goal {\n\t\t\tfmt.Println(ex_in[0].String())\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tvar node Expr\n\tex := make([]*Expr, len(ex_in)-1)\n\n\t\n\t\n\tfor i := range ex {\n\t\tcopy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])\n\n\t\tex[i] = &node\n\t\tfor j := i + 1; j < len(ex_in); j++ {\n\t\t\tnode.left = ex_in[i]\n\t\t\tnode.right = ex_in[j]\n\n\t\t\t\n\t\t\tfor o := op_add; o <= op_div; o++ {\n\t\t\t\tnode.op = o\n\t\t\t\tif solve(ex) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\n\t\t\tnode.left = ex_in[j]\n\t\t\tnode.right = ex_in[i]\n\n\t\t\tnode.op = op_sub\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tnode.op = op_div\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif j < len(ex) {\n\t\t\t\tex[j] = ex_in[j]\n\t\t\t}\n\t\t}\n\t\tex[i] = ex_in[i]\n\t}\n\treturn false\n}\n\nfunc main() {\n\tcards := make([]*Expr, n_cards)\n\trand.Seed(time.Now().Unix())\n\n\tfor k := 0; k < 10; k++ {\n\t\tfor i := 0; i < n_cards; i++ {\n\t\t\tcards[i] = &Expr{op_num, nil, nil,\n\t\t\t\tfrac{rand.Intn(digit_range-1) + 1, 1}}\n\t\t\tfmt.Printf(\" %d\", cards[i].value.num)\n\t\t}\n\t\tfmt.Print(\":  \")\n\t\tif !solve(cards) {\n\t\t\tfmt.Println(\"No solution\")\n\t\t}\n\t}\n}\n"}
{"id": 44567, "name": "24 game_Solve", "Python": "\n \nfrom   __future__ import division, print_function\nfrom   itertools  import permutations, combinations, product, \\\n                         chain\nfrom   pprint     import pprint as pp\nfrom   fractions  import Fraction as F\nimport random, ast, re\nimport sys\n \nif sys.version_info[0] < 3:\n    input = raw_input\n    from itertools import izip_longest as zip_longest\nelse:\n    from itertools import zip_longest\n \n \ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n \ndef ask4():\n    'get four random digits >0 from the player'\n    digits = ''\n    while len(digits) != 4 or not all(d in '123456789' for d in digits):\n        digits = input('Enter the digits to solve for: ')\n        digits = ''.join(digits.strip().split())\n    return list(digits)\n \ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n \ndef check(answer, digits):\n    allowed = set('() +-*/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n \ndef solve(digits):\n    \n    digilen = len(digits)\n    \n    exprlen = 2 * digilen - 1\n    \n    digiperm = sorted(set(permutations(digits)))\n    \n    opcomb   = list(product('+-*/', repeat=digilen-1))\n    \n    brackets = ( [()] + [(x,y)\n                         for x in range(0, exprlen, 2)\n                         for y in range(x+4, exprlen+2, 2)\n                         if (x,y) != (0,exprlen+1)]\n                 + [(0, 3+1, 4+2, 7+3)] ) \n    for d in digiperm:\n        for ops in opcomb:\n            if '/' in ops:\n                d2 = [('F(%s)' % i) for i in d] \n            else:\n                d2 = d\n            ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))\n            for b in brackets:\n                exp = ex[::]\n                for insertpoint, bracket in zip(b, '()'*(len(b)//2)):\n                    exp.insert(insertpoint, bracket)\n                txt = ''.join(exp)\n                try:\n                    num = eval(txt)\n                except ZeroDivisionError:\n                    continue\n                if num == 24:\n                    if '/' in ops:\n                        exp = [ (term if not term.startswith('F(') else term[2])\n                               for term in exp ]\n                    ans = ' '.join(exp).rstrip()\n                    print (\"Solution found:\",ans)\n                    return ans\n    print (\"No solution found for:\", ' '.join(digits))            \n    return '!'\n \ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer == '?':\n            solve(digits)\n            answer = '!'\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if answer == '!!':\n            digits = ask4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            if '/' in answer:\n                \n                answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)\n                                  for char in answer )\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n \nmain()\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nconst (\n\top_num = iota\n\top_add\n\top_sub\n\top_mul\n\top_div\n)\n\ntype frac struct {\n\tnum, denom int\n}\n\n\n\ntype Expr struct {\n\top          int\n\tleft, right *Expr\n\tvalue       frac\n}\n\nvar n_cards = 4\nvar goal = 24\nvar digit_range = 9\n\nfunc (x *Expr) String() string {\n\tif x.op == op_num {\n\t\treturn fmt.Sprintf(\"%d\", x.value.num)\n\t}\n\n\tvar bl1, br1, bl2, br2, opstr string\n\tswitch {\n\tcase x.left.op == op_num:\n\tcase x.left.op >= x.op:\n\tcase x.left.op == op_add && x.op == op_sub:\n\t\tbl1, br1 = \"\", \"\"\n\tdefault:\n\t\tbl1, br1 = \"(\", \")\"\n\t}\n\n\tif x.right.op == op_num || x.op < x.right.op {\n\t\tbl2, br2 = \"\", \"\"\n\t} else {\n\t\tbl2, br2 = \"(\", \")\"\n\t}\n\n\tswitch {\n\tcase x.op == op_add:\n\t\topstr = \" + \"\n\tcase x.op == op_sub:\n\t\topstr = \" - \"\n\tcase x.op == op_mul:\n\t\topstr = \" * \"\n\tcase x.op == op_div:\n\t\topstr = \" / \"\n\t}\n\n\treturn bl1 + x.left.String() + br1 + opstr +\n\t\tbl2 + x.right.String() + br2\n}\n\nfunc expr_eval(x *Expr) (f frac) {\n\tif x.op == op_num {\n\t\treturn x.value\n\t}\n\n\tl, r := expr_eval(x.left), expr_eval(x.right)\n\n\tswitch x.op {\n\tcase op_add:\n\t\tf.num = l.num*r.denom + l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_sub:\n\t\tf.num = l.num*r.denom - l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_mul:\n\t\tf.num = l.num * r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_div:\n\t\tf.num = l.num * r.denom\n\t\tf.denom = l.denom * r.num\n\t\treturn\n\t}\n\treturn\n}\n\nfunc solve(ex_in []*Expr) bool {\n\t\n\t\n\tif len(ex_in) == 1 {\n\t\tf := expr_eval(ex_in[0])\n\t\tif f.denom != 0 && f.num == f.denom*goal {\n\t\t\tfmt.Println(ex_in[0].String())\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tvar node Expr\n\tex := make([]*Expr, len(ex_in)-1)\n\n\t\n\t\n\tfor i := range ex {\n\t\tcopy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])\n\n\t\tex[i] = &node\n\t\tfor j := i + 1; j < len(ex_in); j++ {\n\t\t\tnode.left = ex_in[i]\n\t\t\tnode.right = ex_in[j]\n\n\t\t\t\n\t\t\tfor o := op_add; o <= op_div; o++ {\n\t\t\t\tnode.op = o\n\t\t\t\tif solve(ex) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\n\t\t\tnode.left = ex_in[j]\n\t\t\tnode.right = ex_in[i]\n\n\t\t\tnode.op = op_sub\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tnode.op = op_div\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif j < len(ex) {\n\t\t\t\tex[j] = ex_in[j]\n\t\t\t}\n\t\t}\n\t\tex[i] = ex_in[i]\n\t}\n\treturn false\n}\n\nfunc main() {\n\tcards := make([]*Expr, n_cards)\n\trand.Seed(time.Now().Unix())\n\n\tfor k := 0; k < 10; k++ {\n\t\tfor i := 0; i < n_cards; i++ {\n\t\t\tcards[i] = &Expr{op_num, nil, nil,\n\t\t\t\tfrac{rand.Intn(digit_range-1) + 1, 1}}\n\t\t\tfmt.Printf(\" %d\", cards[i].value.num)\n\t\t}\n\t\tfmt.Print(\":  \")\n\t\tif !solve(cards) {\n\t\t\tfmt.Println(\"No solution\")\n\t\t}\n\t}\n}\n"}
{"id": 44568, "name": "Checkpoint synchronization", "Python": "\n\nimport threading\nimport time\nimport random\n\n\ndef worker(workernum, barrier):\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 1, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n    barrier.wait()\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 2, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n\nbarrier = threading.Barrier(3)\n\nw1 = threading.Thread(target=worker, args=((1,barrier)))\nw2 = threading.Thread(target=worker, args=((2,barrier)))\nw3 = threading.Thread(target=worker, args=((3,barrier)))\n\nw1.start()\nw2.start()\nw3.start()\n", "Go": "package main\n  \nimport (\n    \"log\"\n    \"math/rand\"\n    \"sync\"\n    \"time\"\n)\n\nfunc worker(part string) {\n    log.Println(part, \"worker begins part\")\n    time.Sleep(time.Duration(rand.Int63n(1e6)))\n    log.Println(part, \"worker completes part\")\n    wg.Done()\n}\n\nvar (\n    partList    = []string{\"A\", \"B\", \"C\", \"D\"}\n    nAssemblies = 3\n    wg          sync.WaitGroup\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for c := 1; c <= nAssemblies; c++ {\n        log.Println(\"begin assembly cycle\", c)\n        wg.Add(len(partList))\n        for _, part := range partList {\n            go worker(part)\n        }\n        wg.Wait()\n        log.Println(\"assemble.  cycle\", c, \"complete\")\n    }\n}\n"}
{"id": 44569, "name": "Checkpoint synchronization", "Python": "\n\nimport threading\nimport time\nimport random\n\n\ndef worker(workernum, barrier):\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 1, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n    barrier.wait()\n    \n    sleeptime = random.random()\n    print('Starting worker '+str(workernum)+\" task 2, sleeptime=\"+str(sleeptime))\n    time.sleep(sleeptime)\n    print('Exiting worker'+str(workernum))\n\nbarrier = threading.Barrier(3)\n\nw1 = threading.Thread(target=worker, args=((1,barrier)))\nw2 = threading.Thread(target=worker, args=((2,barrier)))\nw3 = threading.Thread(target=worker, args=((3,barrier)))\n\nw1.start()\nw2.start()\nw3.start()\n", "Go": "package main\n  \nimport (\n    \"log\"\n    \"math/rand\"\n    \"sync\"\n    \"time\"\n)\n\nfunc worker(part string) {\n    log.Println(part, \"worker begins part\")\n    time.Sleep(time.Duration(rand.Int63n(1e6)))\n    log.Println(part, \"worker completes part\")\n    wg.Done()\n}\n\nvar (\n    partList    = []string{\"A\", \"B\", \"C\", \"D\"}\n    nAssemblies = 3\n    wg          sync.WaitGroup\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for c := 1; c <= nAssemblies; c++ {\n        log.Println(\"begin assembly cycle\", c)\n        wg.Add(len(partList))\n        for _, part := range partList {\n            go worker(part)\n        }\n        wg.Wait()\n        log.Println(\"assemble.  cycle\", c, \"complete\")\n    }\n}\n"}
{"id": 44570, "name": "Variable-length quantity", "Python": "def tobits(n, _group=8, _sep='_', _pad=False):\n    'Express n as binary bits with separator'\n    bits = '{0:b}'.format(n)[::-1]\n    if _pad:\n        bits = '{0:0{1}b}'.format(n,\n                                  ((_group+len(bits)-1)//_group)*_group)[::-1]\n        answer = _sep.join(bits[i:i+_group]\n                                 for i in range(0, len(bits), _group))[::-1]\n        answer = '0'*(len(_sep)-1) + answer\n    else:\n        answer = _sep.join(bits[i:i+_group]\n                           for i in range(0, len(bits), _group))[::-1]\n    return answer\n\ndef tovlq(n):\n    return tobits(n, _group=7, _sep='1_', _pad=True)\n\ndef toint(vlq):\n    return int(''.join(vlq.split('_1')), 2)    \n\ndef vlqsend(vlq):\n    for i, byte in enumerate(vlq.split('_')[::-1]):\n        print('Sent byte {0:3}: {1:\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"encoding/binary\"\n)\n\nfunc main() {\n    buf := make([]byte, binary.MaxVarintLen64)\n    for _, x := range []int64{0x200000, 0x1fffff} {\n        v := buf[:binary.PutVarint(buf, x)]\n        fmt.Printf(\"%d encodes into %d bytes: %x\\n\", x, len(v), v)\n        x, _ = binary.Varint(v)\n        fmt.Println(x, \"decoded\")\n    }\n}\n"}
{"id": 44571, "name": "Record sound", "Python": "import pyaudio\n\nchunk = 1024\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 44100\n\np = pyaudio.PyAudio()\n\nstream = p.open(format = FORMAT,\n                channels = CHANNELS,\n                rate = RATE,\n                input = True,\n                frames_per_buffer = chunk)\n\ndata = stream.read(chunk)\nprint [ord(i) for i in data]\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"os/exec\"\n    \"strconv\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    name := \"\"\n    for name == \"\" {\n        fmt.Print(\"Enter output file name (without extension) : \")\n        scanner.Scan()\n        name = scanner.Text()\n        check(scanner.Err())\n    }\n    name += \".wav\"\n\n    rate := 0\n    for rate < 2000 || rate > 192000 {\n        fmt.Print(\"Enter sampling rate in Hz (2000 to 192000) : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        rate, _ = strconv.Atoi(input)\n    }\n    rateS := strconv.Itoa(rate)\n\n    dur := 0.0\n    for dur < 5 || dur > 30 {\n        fmt.Print(\"Enter duration in seconds (5 to 30)        : \")\n        scanner.Scan()\n        input := scanner.Text()\n        check(scanner.Err())\n        dur, _ = strconv.ParseFloat(input, 64)\n    }\n    durS := strconv.FormatFloat(dur, 'f', -1, 64)\n\n    fmt.Println(\"OK, start speaking now...\")\n    \n    args := []string{\"-r\", rateS, \"-f\", \"S16_LE\", \"-d\", durS, name}\n    cmd := exec.Command(\"arecord\", args...)\n    err := cmd.Run()\n    check(err)\n\n    fmt.Printf(\"'%s' created on disk and will now be played back...\\n\", name)\n    cmd = exec.Command(\"aplay\", name)\n    err = cmd.Run()\n    check(err)\n    fmt.Println(\"Play-back completed.\")\n}\n"}
{"id": 44572, "name": "SHA-256 Merkle tree", "Python": "\n\n\nimport argh\nimport hashlib  \nimport sys\n  \n@argh.arg('filename', nargs='?', default=None)\ndef main(filename, block_size=1024*1024):\n    if filename:\n        fin = open(filename, 'rb')\n    else: \n        fin = sys.stdin\n    \n    stack = []\n    block = fin.read(block_size)\n    while block:\n        \n        node = (0, hashlib.sha256(block).digest())\n        stack.append(node)\n\n        \n        while len(stack) >= 2 and stack[-2][0] == stack[-1][0]:\n            a = stack[-2]\n            b = stack[-1]\n            l = a[0]\n            stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())]\n\n        block = fin.read(block_size)\n    \n    while len(stack) > 1:\n        \n        a = stack[-2]\n        b = stack[-1]\n        al = a[0]\n        bl = b[0]\n        stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())]\n\n    print(stack[0][1].hex())\n\n\nargh.dispatch_command(main)\n", "Go": "package main\n\nimport (\n    \"crypto/sha256\"\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"os\"\n)\n\nfunc main() {\n    const blockSize = 1024\n    f, err := os.Open(\"title.png\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n\n    var hashes [][]byte\n    buffer := make([]byte, blockSize)\n    h := sha256.New()\n    for {\n        bytesRead, err := f.Read(buffer)\n        if err != nil {\n            if err != io.EOF {\n                log.Fatal(err)\n            }\n            break\n        }\n        h.Reset()\n        h.Write(buffer[:bytesRead])\n        hashes = append(hashes, h.Sum(nil))\n    }\n    buffer = make([]byte, 64)\n    for len(hashes) > 1 {\n        var hashes2 [][]byte\n        for i := 0; i < len(hashes); i += 2 {\n            if i < len(hashes)-1 {                \n                copy(buffer, hashes[i])\n                copy(buffer[32:], hashes[i+1])\n                h.Reset()\n                h.Write(buffer)\n                hashes2 = append(hashes2, h.Sum(nil))\n            } else {\n                hashes2 = append(hashes2, hashes[i])\n            }\n        }\n        hashes = hashes2\n    }\n    fmt.Printf(\"%x\", hashes[0])\n    fmt.Println()\n}\n"}
{"id": 44573, "name": "String case", "Python": "s = \"alphaBETA\"\nprint s.upper() \nprint s.lower() \n\nprint s.swapcase() \n\nprint \"fOo bAR\".capitalize() \nprint \"fOo bAR\".title() \n\nimport string\nprint string.capwords(\"fOo bAR\") \n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    show(\"alphaBETA\")\n    show(\"alpha BETA\")\n    \n    show(\"Ǆǈǌ\")\n    \n    show(\"o'hare O'HARE o’hare don't\")\n}\n\nfunc show(s string) {\n    fmt.Println(\"\\nstring:         \",\n        s, \" len:\", utf8.RuneCountInString(s), \"runes\") \n    fmt.Println(\"All upper case: \", strings.ToUpper(s)) \n    fmt.Println(\"All lower case: \", strings.ToLower(s)) \n    fmt.Println(\"All title case: \", strings.ToTitle(s)) \n    fmt.Println(\"Title words:    \", strings.Title(s))   \n    fmt.Println(\"Swapping case:  \",                     \n        strings.Map(unicode.SimpleFold, s))\n}\n"}
{"id": 44574, "name": "User input_Graphical", "Python": "from javax.swing import JOptionPane\n\ndef to_int(n, default=0):\n    try:\n        return int(n)\n    except ValueError:\n        return default\n\nnumber = to_int(JOptionPane.showInputDialog (\"Enter an Integer\")) \nprintln(number)\n\na_string = JOptionPane.showInputDialog (\"Enter a String\")\nprintln(a_string)\n", "Go": "package main\n\nimport (\n    \"github.com/gotk3/gotk3/gtk\"\n    \"log\"\n    \"math/rand\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc validateInput(window *gtk.Window, str1, str2 string) bool {\n    n, err := strconv.ParseFloat(str2, 64)\n    if len(str1) == 0 || err != nil || n != 75000 {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid input\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return false\n    }\n    return true\n}\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetTitle(\"Rosetta Code\")\n    window.SetPosition(gtk.WIN_POS_CENTER)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)\n    check(err, \"Unable to create vertical box:\")\n    vbox.SetBorderWidth(1)\n\n    hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create first horizontal box:\")\n\n    hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create second horizontal box:\")\n\n    label, err := gtk.LabelNew(\"Enter a string and the number 75000   \\n\")\n    check(err, \"Unable to create label:\")\n\n    sel, err := gtk.LabelNew(\"String:      \")\n    check(err, \"Unable to create string entry label:\")\n\n    nel, err := gtk.LabelNew(\"Number: \")\n    check(err, \"Unable to create number entry label:\")\n\n    se, err := gtk.EntryNew()\n    check(err, \"Unable to create string entry:\")\n\n    ne, err := gtk.EntryNew()\n    check(err, \"Unable to create number entry:\")\n\n    hbox1.PackStart(sel, false, false, 2)\n    hbox1.PackStart(se, false, false, 2)\n\n    hbox2.PackStart(nel, false, false, 2)\n    hbox2.PackStart(ne, false, false, 2)\n\n    \n    ab, err := gtk.ButtonNewWithLabel(\"Accept\")\n    check(err, \"Unable to create accept button:\")\n    ab.Connect(\"clicked\", func() {\n        \n        str1, _ := se.GetText()\n        str2, _ := ne.GetText()\n        if validateInput(window, str1, str2) {\n            window.Destroy() \n        }\n    })\n\n    vbox.Add(label)\n    vbox.Add(hbox1)\n    vbox.Add(hbox2)\n    vbox.Add(ab)\n    window.Add(vbox)\n\n    window.ShowAll()\n    gtk.Main()\n}\n"}
{"id": 44575, "name": "Sierpinski arrowhead curve", "Python": "t = { 'x': 20, 'y': 30, 'a': 60 }\n\ndef setup():\n    size(450, 400)\n    background(0, 0, 200)\n    stroke(-1)\n    sc(7, 400, -60)\n\ndef sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5):\n    if o:\n        o -= 1\n        l *= HALF\n        sc(o, l, -a)[A] += a\n        sc(o, l, a)[A] += a\n        sc(o, l, -a)\n    else:\n        x, y = s[X], s[Y]\n        s[X] += cos(radians(s[A])) * l\n        s[Y] += sin(radians(s[A])) * l\n        line(x, y, s[X], s[Y])\n\n    return s\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"math\"\n)\n\nvar (\n    width  = 770.0\n    height = 770.0\n    dc     = gg.NewContext(int(width), int(height))\n    iy     = 1.0\n    theta  = 0\n)\n\nvar cx, cy, h float64\n\nfunc arrowhead(order int, length float64) {\n    \n    if order&1 == 0 {\n        curve(order, length, 60)\n    } else {\n        turn(60)\n        curve(order, length, -60)\n    }\n    drawLine(length) \n}\n\nfunc drawLine(length float64) {\n    dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h)\n    rads := gg.Radians(float64(theta))\n    cx += length * math.Cos(rads)\n    cy += length * math.Sin(rads)\n}\n\nfunc turn(angle int) {\n    theta = (theta + angle) % 360\n}\n\nfunc curve(order int, length float64, angle int) {\n    if order == 0 {\n        drawLine(length)\n    } else {\n        curve(order-1, length/2, -angle)\n        turn(angle)\n        curve(order-1, length/2, angle)\n        turn(angle)\n        curve(order-1, length/2, -angle)\n    }\n}\n\nfunc main() {\n    dc.SetRGB(0, 0, 0) \n    dc.Clear()\n    order := 6\n    if order&1 == 0 {\n        iy = -1 \n    }\n    cx, cy = width/2, height\n    h = cx / 2\n    arrowhead(order, cx)\n    dc.SetRGB255(255, 0, 255) \n    dc.SetLineWidth(2)\n    dc.Stroke()\n    dc.SavePNG(\"sierpinski_arrowhead_curve.png\")\n}\n"}
{"id": 44576, "name": "Text processing_1", "Python": "import fileinput\nimport sys\n\nnodata = 0;             \nnodata_max=-1;          \nnodata_maxline=[];      \n\ntot_file = 0            \nnum_file = 0            \n\ninfiles = sys.argv[1:]\n\nfor line in fileinput.input():\n  tot_line=0;             \n  num_line=0;             \n\n  \n  field = line.split()\n  date  = field[0]\n  data  = [float(f) for f in field[1::2]]\n  flags = [int(f)   for f in field[2::2]]\n\n  for datum, flag in zip(data, flags):\n    if flag<1:\n      nodata += 1\n    else:\n      \n      if nodata_max==nodata and nodata>0:\n        nodata_maxline.append(date)\n      if nodata_max<nodata and nodata>0:\n        nodata_max=nodata\n        nodata_maxline=[date]\n      \n      nodata=0; \n      \n      tot_line += datum\n      num_line += 1\n\n  \n  tot_file += tot_line\n  num_file += num_line\n\n  print \"Line: %11s  Reject: %2i  Accept: %2i  Line_tot: %10.3f  Line_avg: %10.3f\" % (\n        date, \n        len(data) -num_line, \n        num_line, tot_line, \n        tot_line/num_line if (num_line>0) else 0)\n\nprint \"\"\nprint \"File(s)  = %s\" % (\", \".join(infiles),)\nprint \"Total    = %10.3f\" % (tot_file,)\nprint \"Readings = %6i\" % (num_file,)\nprint \"Average  = %10.3f\" % (tot_file / num_file,)\n\nprint \"\\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s\" % (\n    nodata_max, \", \".join(nodata_maxline))\n", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tfilename = \"readings.txt\"\n\treadings = 24             \n\tfields   = readings*2 + 1 \n)\n\nfunc main() {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\tvar (\n\t\tbadRun, maxRun   int\n\t\tbadDate, maxDate string\n\t\tfileSum          float64\n\t\tfileAccept       int\n\t)\n\tendBadRun := func() {\n\t\tif badRun > maxRun {\n\t\t\tmaxRun = badRun\n\t\t\tmaxDate = badDate\n\t\t}\n\t\tbadRun = 0\n\t}\n\ts := bufio.NewScanner(file)\n\tfor s.Scan() {\n\t\tf := strings.Fields(s.Text())\n\t\tif len(f) != fields {\n\t\t\tlog.Fatal(\"unexpected format,\", len(f), \"fields.\")\n\t\t}\n\t\tvar accept int\n\t\tvar sum float64\n\t\tfor i := 1; i < fields; i += 2 {\n\t\t\tflag, err := strconv.Atoi(f[i+1])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tif flag <= 0 { \n\t\t\t\tif badRun++; badRun == 1 {\n\t\t\t\t\tbadDate = f[0]\n\t\t\t\t}\n\t\t\t} else { \n\t\t\t\tendBadRun()\n\t\t\t\tvalue, err := strconv.ParseFloat(f[i], 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tsum += value\n\t\t\t\taccept++\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Line: %s  Reject %2d  Accept: %2d  Line_tot:%9.3f\",\n\t\t\tf[0], readings-accept, accept, sum)\n\t\tif accept > 0 {\n\t\t\tfmt.Printf(\"  Line_avg:%8.3f\\n\", sum/float64(accept))\n\t\t} else {\n\t\t\tfmt.Println()\n\t\t}\n\t\tfileSum += sum\n\t\tfileAccept += accept\n\t}\n\tif err := s.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tendBadRun()\n\n\tfmt.Println(\"\\nFile     =\", filename)\n\tfmt.Printf(\"Total    = %.3f\\n\", fileSum)\n\tfmt.Println(\"Readings = \", fileAccept)\n\tif fileAccept > 0 {\n\t\tfmt.Printf(\"Average  =  %.3f\\n\", fileSum/float64(fileAccept))\n\t}\n\tif maxRun == 0 {\n\t\tfmt.Println(\"\\nAll data valid.\")\n\t} else {\n\t\tfmt.Printf(\"\\nMax data gap = %d, beginning on line %s.\\n\",\n\t\t\tmaxRun, maxDate)\n\t}\n}\n"}
{"id": 44577, "name": "MD5", "Python": ">>> import hashlib\n>>> \n>>> tests = (\n  (b\"\", 'd41d8cd98f00b204e9800998ecf8427e'),\n  (b\"a\", '0cc175b9c0f1b6a831c399e269772661'),\n  (b\"abc\", '900150983cd24fb0d6963f7d28e17f72'),\n  (b\"message digest\", 'f96b697d7cb7938d525a2f31aaf161d0'),\n  (b\"abcdefghijklmnopqrstuvwxyz\", 'c3fcd3d76192e4007dfb496cca67e13b'),\n  (b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", 'd174ab98d277d9f5a5611c2c9f419d9f'),\n  (b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\", '57edf4a22be3c955ac49da2e2107b67a') )\n>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden\n\n>>>\n", "Go": "package main\n\nimport (\n    \"crypto/md5\"\n    \"fmt\"\n)\n\nfunc main() {\n    for _, p := range [][2]string{\n        \n        {\"d41d8cd98f00b204e9800998ecf8427e\", \"\"},\n        {\"0cc175b9c0f1b6a831c399e269772661\", \"a\"},\n        {\"900150983cd24fb0d6963f7d28e17f72\", \"abc\"},\n        {\"f96b697d7cb7938d525a2f31aaf161d0\", \"message digest\"},\n        {\"c3fcd3d76192e4007dfb496cca67e13b\", \"abcdefghijklmnopqrstuvwxyz\"},\n        {\"d174ab98d277d9f5a5611c2c9f419d9f\",\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"},\n        {\"57edf4a22be3c955ac49da2e2107b67a\", \"12345678901234567890\" +\n            \"123456789012345678901234567890123456789012345678901234567890\"},\n        \n        {\"e38ca1d920c4b8b8d3946b2c72f01680\",\n            \"The quick brown fox jumped over the lazy dog's back\"},\n    } {\n        validate(p[0], p[1])\n    }\n}\n\nvar h = md5.New()\n\nfunc validate(check, s string) {\n    h.Reset()\n    h.Write([]byte(s))\n    sum := fmt.Sprintf(\"%x\", h.Sum(nil))\n    if sum != check {\n        fmt.Println(\"MD5 fail\")\n        fmt.Println(\"  for string,\", s)\n        fmt.Println(\"  expected:  \", check)\n        fmt.Println(\"  got:       \", sum)\n    }\n}\n"}
{"id": 44578, "name": "Aliquot sequence classifications", "Python": "from proper_divisors import proper_divs\nfrom functools import lru_cache\n\n\n@lru_cache()\ndef pdsum(n): \n    return sum(proper_divs(n))\n    \n    \ndef aliquot(n, maxlen=16, maxterm=2**47):\n    if n == 0:\n        return 'terminating', [0]\n    s, slen, new = [n], 1, n\n    while slen <= maxlen and new < maxterm:\n        new = pdsum(s[-1])\n        if new in s:\n            if s[0] == new:\n                if slen == 1:\n                    return 'perfect', s\n                elif slen == 2:\n                    return 'amicable', s\n                else:\n                    return 'sociable of length %i' % slen, s\n            elif s[-1] == new:\n                return 'aspiring', s\n            else:\n                return 'cyclic back to %i' % new, s\n        elif new == 0:\n            return 'terminating', s + [0]\n        else:\n            s.append(new)\n            slen += 1\n    else:\n        return 'non-terminating', s\n                \nif __name__ == '__main__':\n    for n in range(1, 11): \n        print('%s: %r' % aliquot(n))\n    print()\n    for n in [11, 12, 28, 496, 220, 1184,  12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: \n        print('%s: %r' % aliquot(n))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nconst threshold = uint64(1) << 47\n\nfunc indexOf(s []uint64, search uint64) int {\n    for i, e := range s {\n        if e == search {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc contains(s []uint64, search uint64) bool {\n    return indexOf(s, search) > -1\n}\n\nfunc maxOf(i1, i2 int) int {\n    if i1 > i2 {\n        return i1\n    }\n    return i2\n}\n\nfunc sumProperDivisors(n uint64) uint64 {\n    if n < 2 {\n        return 0\n    }\n    sqrt := uint64(math.Sqrt(float64(n)))\n    sum := uint64(1)\n    for i := uint64(2); i <= sqrt; i++ {\n        if n % i != 0 {\n            continue\n        }\n        sum += i + n / i\n    }\n    if sqrt * sqrt == n {\n        sum -= sqrt\n    }\n    return sum\n}\n\nfunc classifySequence(k uint64) ([]uint64, string) {\n    if k == 0 {\n        panic(\"Argument must be positive.\")\n    }\n    last := k\n    var seq []uint64\n    seq = append(seq, k)\n    for {\n        last = sumProperDivisors(last)\n        seq = append(seq, last)\n        n := len(seq)\n        aliquot := \"\"\n        switch {\n        case last == 0:\n            aliquot = \"Terminating\"\n        case n == 2 && last == k:\n            aliquot = \"Perfect\"\n        case n == 3 && last == k:\n            aliquot = \"Amicable\"\n        case n >= 4 && last == k:\n            aliquot = fmt.Sprintf(\"Sociable[%d]\", n - 1)\n        case last == seq[n - 2]:\n            aliquot = \"Aspiring\"\n        case contains(seq[1 : maxOf(1, n - 2)], last):\n            aliquot = fmt.Sprintf(\"Cyclic[%d]\", n - 1 - indexOf(seq[:], last))\n        case n == 16 || last > threshold:\n            aliquot = \"Non-Terminating\"\n        }\n        if aliquot != \"\" {\n            return seq, aliquot\n        }\n    }\n}\n\nfunc joinWithCommas(seq []uint64) string {\n    res := fmt.Sprint(seq)\n    res = strings.Replace(res, \" \", \", \", -1)\n    return res\n}\n\nfunc main() {\n    fmt.Println(\"Aliquot classifications - periods for Sociable/Cyclic in square brackets:\\n\")\n    for k := uint64(1); k <= 10; k++ {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%2d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    s := []uint64{\n        11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,\n    }\n    for _, k := range s {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%7d: %-15s %s\\n\",  k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    k := uint64(15355717786080)\n    seq, aliquot := classifySequence(k)\n    fmt.Printf(\"%d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n}\n"}
{"id": 44579, "name": "Aliquot sequence classifications", "Python": "from proper_divisors import proper_divs\nfrom functools import lru_cache\n\n\n@lru_cache()\ndef pdsum(n): \n    return sum(proper_divs(n))\n    \n    \ndef aliquot(n, maxlen=16, maxterm=2**47):\n    if n == 0:\n        return 'terminating', [0]\n    s, slen, new = [n], 1, n\n    while slen <= maxlen and new < maxterm:\n        new = pdsum(s[-1])\n        if new in s:\n            if s[0] == new:\n                if slen == 1:\n                    return 'perfect', s\n                elif slen == 2:\n                    return 'amicable', s\n                else:\n                    return 'sociable of length %i' % slen, s\n            elif s[-1] == new:\n                return 'aspiring', s\n            else:\n                return 'cyclic back to %i' % new, s\n        elif new == 0:\n            return 'terminating', s + [0]\n        else:\n            s.append(new)\n            slen += 1\n    else:\n        return 'non-terminating', s\n                \nif __name__ == '__main__':\n    for n in range(1, 11): \n        print('%s: %r' % aliquot(n))\n    print()\n    for n in [11, 12, 28, 496, 220, 1184,  12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: \n        print('%s: %r' % aliquot(n))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nconst threshold = uint64(1) << 47\n\nfunc indexOf(s []uint64, search uint64) int {\n    for i, e := range s {\n        if e == search {\n            return i\n        }\n    }\n    return -1\n}\n\nfunc contains(s []uint64, search uint64) bool {\n    return indexOf(s, search) > -1\n}\n\nfunc maxOf(i1, i2 int) int {\n    if i1 > i2 {\n        return i1\n    }\n    return i2\n}\n\nfunc sumProperDivisors(n uint64) uint64 {\n    if n < 2 {\n        return 0\n    }\n    sqrt := uint64(math.Sqrt(float64(n)))\n    sum := uint64(1)\n    for i := uint64(2); i <= sqrt; i++ {\n        if n % i != 0 {\n            continue\n        }\n        sum += i + n / i\n    }\n    if sqrt * sqrt == n {\n        sum -= sqrt\n    }\n    return sum\n}\n\nfunc classifySequence(k uint64) ([]uint64, string) {\n    if k == 0 {\n        panic(\"Argument must be positive.\")\n    }\n    last := k\n    var seq []uint64\n    seq = append(seq, k)\n    for {\n        last = sumProperDivisors(last)\n        seq = append(seq, last)\n        n := len(seq)\n        aliquot := \"\"\n        switch {\n        case last == 0:\n            aliquot = \"Terminating\"\n        case n == 2 && last == k:\n            aliquot = \"Perfect\"\n        case n == 3 && last == k:\n            aliquot = \"Amicable\"\n        case n >= 4 && last == k:\n            aliquot = fmt.Sprintf(\"Sociable[%d]\", n - 1)\n        case last == seq[n - 2]:\n            aliquot = \"Aspiring\"\n        case contains(seq[1 : maxOf(1, n - 2)], last):\n            aliquot = fmt.Sprintf(\"Cyclic[%d]\", n - 1 - indexOf(seq[:], last))\n        case n == 16 || last > threshold:\n            aliquot = \"Non-Terminating\"\n        }\n        if aliquot != \"\" {\n            return seq, aliquot\n        }\n    }\n}\n\nfunc joinWithCommas(seq []uint64) string {\n    res := fmt.Sprint(seq)\n    res = strings.Replace(res, \" \", \", \", -1)\n    return res\n}\n\nfunc main() {\n    fmt.Println(\"Aliquot classifications - periods for Sociable/Cyclic in square brackets:\\n\")\n    for k := uint64(1); k <= 10; k++ {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%2d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    s := []uint64{\n        11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,\n    }\n    for _, k := range s {\n        seq, aliquot := classifySequence(k)\n        fmt.Printf(\"%7d: %-15s %s\\n\",  k, aliquot, joinWithCommas(seq))\n    }\n    fmt.Println()\n\n    k := uint64(15355717786080)\n    seq, aliquot := classifySequence(k)\n    fmt.Printf(\"%d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n}\n"}
{"id": 44580, "name": "Date manipulation", "Python": "import datetime\n\ndef mt():\n\tdatime1=\"March 7 2009 7:30pm EST\"\n\tformatting = \"%B %d %Y %I:%M%p \"\n\tdatime2 = datime1[:-3]  \n\ttdelta = datetime.timedelta(hours=12)\t\t\n\ts3 = datetime.datetime.strptime(datime2, formatting)\n\tdatime2 = s3+tdelta\n\tprint datime2.strftime(\"%B %d %Y %I:%M%p %Z\") + datime1[-3:]\n\nmt()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nconst taskDate = \"March 7 2009 7:30pm EST\"\nconst taskFormat = \"January 2 2006 3:04pm MST\"\n\nfunc main() {\n    if etz, err := time.LoadLocation(\"US/Eastern\"); err == nil {\n        time.Local = etz\n    }\n    fmt.Println(\"Input:             \", taskDate)\n    t, err := time.Parse(taskFormat, taskDate)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    t = t.Add(12 * time.Hour)\n    fmt.Println(\"+12 hrs:           \", t)\n    if _, offset := t.Zone(); offset == 0 {\n        fmt.Println(\"No time zone info.\")\n        return\n    }\n    atz, err := time.LoadLocation(\"US/Arizona\")\n    if err == nil {\n        fmt.Println(\"+12 hrs in Arizona:\", t.In(atz))\n    }\n}\n"}
{"id": 44581, "name": "Sorting algorithms_Sleep sort", "Python": "from time import sleep\nfrom threading import Timer\n\ndef sleepsort(values):\n    sleepsort.result = []\n    def add1(x):\n        sleepsort.result.append(x)\n    mx = values[0]\n    for v in values:\n        if mx < v: mx = v\n        Timer(v, add1, [v]).start()\n    sleep(mx+1)\n    return sleepsort.result\n\nif __name__ == '__main__':\n    x = [3,2,4,7,3,6,9,1]\n    if sleepsort(x) == sorted(x):\n        print('sleep sort worked for:',x)\n    else:\n        print('sleep sort FAILED for:',x)\n", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc main() {\n\tout := make(chan uint64)\n\tfor _, a := range os.Args[1:] {\n\t\ti, err := strconv.ParseUint(a, 10, 64)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tgo func(n uint64) {\n\t\t\ttime.Sleep(time.Duration(n) * time.Millisecond)\n\t\t\tout <- n\n\t\t}(i)\n\t}\n\tfor _ = range os.Args[1:] {\n\t\tfmt.Println(<-out)\n\t}\n}\n"}
{"id": 44582, "name": "Loops_Nested", "Python": "from random import randint\n\ndef do_scan(mat):\n    for row in mat:\n        for item in row:\n            print item,\n            if item == 20:\n                print\n                return\n        print\n    print\n\nmat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]\ndo_scan(mat)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n\n    values := make([][]int, 10)\n    for i := range values {\n        values[i] = make([]int, 10)\n        for j := range values[i] {\n            values[i][j] = rand.Intn(20) + 1\n        }\n    }\n\nouterLoop:\n    for i, row := range values {\n        fmt.Printf(\"%3d)\", i)\n        for _, value := range row {\n            fmt.Printf(\" %3d\", value)\n            if value == 20 {\n                break outerLoop\n            }\n        }\n        fmt.Printf(\"\\n\")\n    }\n    fmt.Printf(\"\\n\")\n}\n"}
{"id": 44583, "name": "Pythagorean triples", "Python": "from fractions import gcd\n\n\ndef pt1(maxperimeter=100):\n    \n    trips = []\n    for a in range(1, maxperimeter):\n        aa = a*a\n        for b in range(a, maxperimeter-a+1):\n            bb = b*b\n            for c in range(b, maxperimeter-b-a+1):\n                cc = c*c\n                if a+b+c > maxperimeter or cc > aa + bb: break\n                if aa + bb == cc:\n                    trips.append((a,b,c, gcd(a, b) == 1))\n    return trips\n\ndef pytrip(trip=(3,4,5),perim=100, prim=1):\n    a0, b0, c0 = a, b, c = sorted(trip)\n    t, firstprim = set(), prim>0\n    while a + b + c <= perim:\n        t.add((a, b, c, firstprim>0))\n        a, b, c, firstprim = a+a0, b+b0, c+c0, False\n    \n    t2 = set()\n    for a, b, c, firstprim in t:\n        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7\n        if  a5 - b5 + c7 <= perim:\n            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)\n        if  a5 + b5 + c7 <= perim:\n            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)\n        if -a5 + b5 + c7 <= perim:\n            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)\n    return t | t2\n\ndef pt2(maxperimeter=100):\n    \n    trips = pytrip((3,4,5), maxperimeter, 1)\n    return trips\n\ndef printit(maxperimeter=100, pt=pt1):\n    trips = pt(maxperimeter)\n    print(\"  Up to a perimeter of %i there are %i triples, of which %i are primitive\"\n          % (maxperimeter,\n             len(trips),\n             len([prim for a,b,c,prim in trips if prim])))\n  \nfor algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):\n    print(algo.__doc__)\n    for maxperimeter in range(mn, mx+1, mn):\n        printit(maxperimeter, algo)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar total, prim, maxPeri int64\n\nfunc newTri(s0, s1, s2 int64) {\n    if p := s0 + s1 + s2; p <= maxPeri {\n        prim++\n        total += maxPeri / p\n        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)\n        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)\n        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)\n    }\n}\n\nfunc main() {\n    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {\n        prim = 0\n        total = 0\n        newTri(3, 4, 5)\n        fmt.Printf(\"Up to %d:  %d triples, %d primitives\\n\",\n            maxPeri, total, prim)\n    }\n}\n"}
{"id": 44584, "name": "Pythagorean triples", "Python": "from fractions import gcd\n\n\ndef pt1(maxperimeter=100):\n    \n    trips = []\n    for a in range(1, maxperimeter):\n        aa = a*a\n        for b in range(a, maxperimeter-a+1):\n            bb = b*b\n            for c in range(b, maxperimeter-b-a+1):\n                cc = c*c\n                if a+b+c > maxperimeter or cc > aa + bb: break\n                if aa + bb == cc:\n                    trips.append((a,b,c, gcd(a, b) == 1))\n    return trips\n\ndef pytrip(trip=(3,4,5),perim=100, prim=1):\n    a0, b0, c0 = a, b, c = sorted(trip)\n    t, firstprim = set(), prim>0\n    while a + b + c <= perim:\n        t.add((a, b, c, firstprim>0))\n        a, b, c, firstprim = a+a0, b+b0, c+c0, False\n    \n    t2 = set()\n    for a, b, c, firstprim in t:\n        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7\n        if  a5 - b5 + c7 <= perim:\n            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)\n        if  a5 + b5 + c7 <= perim:\n            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)\n        if -a5 + b5 + c7 <= perim:\n            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)\n    return t | t2\n\ndef pt2(maxperimeter=100):\n    \n    trips = pytrip((3,4,5), maxperimeter, 1)\n    return trips\n\ndef printit(maxperimeter=100, pt=pt1):\n    trips = pt(maxperimeter)\n    print(\"  Up to a perimeter of %i there are %i triples, of which %i are primitive\"\n          % (maxperimeter,\n             len(trips),\n             len([prim for a,b,c,prim in trips if prim])))\n  \nfor algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):\n    print(algo.__doc__)\n    for maxperimeter in range(mn, mx+1, mn):\n        printit(maxperimeter, algo)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar total, prim, maxPeri int64\n\nfunc newTri(s0, s1, s2 int64) {\n    if p := s0 + s1 + s2; p <= maxPeri {\n        prim++\n        total += maxPeri / p\n        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)\n        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)\n        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)\n    }\n}\n\nfunc main() {\n    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {\n        prim = 0\n        total = 0\n        newTri(3, 4, 5)\n        fmt.Printf(\"Up to %d:  %d triples, %d primitives\\n\",\n            maxPeri, total, prim)\n    }\n}\n"}
{"id": 44585, "name": "Remove duplicate elements", "Python": "items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc uniq(list []int) []int {\n\tunique_set := make(map[int]bool, len(list))\n\tfor _, x := range list {\n\t\tunique_set[x] = true\n\t}\n\tresult := make([]int, 0, len(unique_set))\n\tfor x := range unique_set {\n\t\tresult = append(result, x)\n\t}\n\treturn result\n}\n\nfunc main() {\n\tfmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) \n}\n"}
{"id": 44586, "name": "Look-and-say sequence", "Python": "def lookandsay(number):\n    result = \"\"\n\n    repeat = number[0]\n    number = number[1:]+\" \"\n    times = 1\n\n    for actual in number:\n        if actual != repeat:\n            result += str(times)+repeat\n            times = 1\n            repeat = actual\n        else:\n            times += 1\n\n    return result\n\nnum = \"1\"\n\nfor i in range(10):\n    print num\n    num = lookandsay(num)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc lss(s string) (r string) {\n    c := s[0]\n    nc := 1\n    for i := 1; i < len(s); i++ {\n        d := s[i]\n        if d == c {\n            nc++\n            continue\n        }\n        r += strconv.Itoa(nc) + string(c)\n        c = d\n        nc = 1\n    }\n    return r + strconv.Itoa(nc) + string(c)\n}\n\nfunc main() {\n    s := \"1\"\n    fmt.Println(s)\n    for i := 0; i < 8; i++ {\n        s = lss(s)\n        fmt.Println(s)\n    }\n}\n"}
{"id": 44587, "name": "Totient function", "Python": "from math import gcd\n\ndef  φ(n):\n    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)\n\nif __name__ == '__main__':\n    def is_prime(n):\n        return φ(n) == n - 1\n    \n    for n in range(1, 26):\n        print(f\" φ({n}) == {φ(n)}{', is prime' if is_prime(n)  else ''}\")\n    count = 0\n    for n in range(1, 10_000 + 1):\n        count += is_prime(n)\n        if n in {100, 1000, 10_000}:\n            print(f\"Primes up to {n}: {count}\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    fmt.Println(\" n  phi   prime\")\n    fmt.Println(\"---------------\")\n    count := 0\n    for n := 1; n <= 25; n++ {\n        tot := totient(n)\n        isPrime := n-1 == tot\n        if isPrime {\n            count++\n        }\n        fmt.Printf(\"%2d   %2d   %t\\n\", n, tot, isPrime)\n    }\n    fmt.Println(\"\\nNumber of primes up to 25     =\", count)\n    for n := 26; n <= 100000; n++ {\n        tot := totient(n)\n        if tot == n-1 {\n            count++\n        }\n        if n == 100 || n == 1000 || n%10000 == 0 {\n            fmt.Printf(\"\\nNumber of primes up to %-6d = %d\\n\", n, count)\n        }\n    }\n}\n"}
{"id": 44588, "name": "Conditional structures", "Python": "if x == 0:\n    foo()\nelif x == 1:\n    bar()\nelif x == 2:\n    baz()\nelse:\n    qux()\n\nmatch x:\n    0 => foo()\n    1 => bar()\n    2 => baz()\n    _ => qux()\n\n(a) ? b : c\n", "Go": "if booleanExpression {\n    statements\n}\n"}
{"id": 44589, "name": "Fractran", "Python": "from fractions import Fraction\n\ndef fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'\n                        '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'\n                        '13 / 11, 15 / 14, 15 / 2, 55 / 1'):\n    flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]\n\n    n = Fraction(n)\n    while True:\n        yield n.numerator\n        for f in flist:\n            if (n * f).denominator == 1:\n                break\n        else:\n            break\n        n *= f\n    \nif __name__ == '__main__':\n    n, m = 2, 15\n    print('First %i members of fractran(%i):\\n  ' % (m, n) +\n          ', '.join(str(f) for f,i in zip(fractran(n), range(m))))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc compile(src string) ([]big.Rat, bool) {\n    s := strings.Fields(src)\n    r := make([]big.Rat, len(s))\n    for i, s1 := range s {\n        if _, ok := r[i].SetString(s1); !ok {\n            return nil, false\n        }\n    }\n    return r, true\n}\n\nfunc exec(p []big.Rat, n *big.Int, limit int) {\n    var q, r big.Int\nrule:\n    for i := 0; i < limit; i++ {\n        fmt.Printf(\"%d \", n)\n        for j := range p {\n            q.QuoRem(n, p[j].Denom(), &r)\n            if r.BitLen() == 0 {\n                n.Mul(&q, p[j].Num())\n                continue rule\n            }\n        }\n        break\n    }\n    fmt.Println()\n}\n\nfunc usage() {\n    log.Fatal(\"usage: ft <limit> <n> <prog>\")\n}\n\nfunc main() {\n    if len(os.Args) != 4 {\n        usage()\n    }\n    limit, err := strconv.Atoi(os.Args[1])\n    if err != nil {\n        usage()\n    }\n    var n big.Int\n    _, ok := n.SetString(os.Args[2], 10)\n    if !ok {\n        usage()\n    }\n    p, ok := compile(os.Args[3])\n    if !ok {\n        usage()\n    }\n    exec(p, &n, limit)\n}\n"}
{"id": 44590, "name": "Sorting algorithms_Stooge sort", "Python": ">>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]\n>>> def stoogesort(L, i=0, j=None):\n\tif j is None:\n\t\tj = len(L) - 1\n\tif L[j] < L[i]:\n\t\tL[i], L[j] = L[j], L[i]\n\tif j - i > 1:\n\t\tt = (j - i + 1) // 3\n\t\tstoogesort(L, i  , j-t)\n\t\tstoogesort(L, i+t, j  )\n\t\tstoogesort(L, i  , j-t)\n\treturn L\n\n>>> stoogesort(data)\n[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    stoogesort(a)\n    fmt.Println(\"after: \", a)\n    fmt.Println(\"nyuk nyuk nyuk\")\n}\n\nfunc stoogesort(a []int) {\n    last := len(a) - 1\n    if a[last] < a[0] {\n        a[0], a[last] = a[last], a[0]\n    }\n    if last > 1 {\n        t := len(a) / 3\n        stoogesort(a[:len(a)-t])\n        stoogesort(a[t:])\n        stoogesort(a[:len(a)-t])\n    }\n}\n"}
{"id": 44591, "name": "Galton box animation", "Python": "\n\nimport sys, os\nimport random\nimport time\n\ndef print_there(x, y, text):\n     sys.stdout.write(\"\\x1b7\\x1b[%d;%df%s\\x1b8\" % (x, y, text))\n     sys.stdout.flush()\n\n\nclass Ball():\n    def __init__(self):\n        self.x = 0\n        self.y = 0\n        \n    def update(self):\n        self.x += random.randint(0,1)\n        self.y += 1\n\n    def fall(self):\n        self.y +=1\n\n\nclass Board():\n    def __init__(self, width, well_depth, N):\n        self.balls = []\n        self.fallen = [0] * (width + 1)\n        self.width = width\n        self.well_depth = well_depth\n        self.N = N\n        self.shift = 4\n        \n    def update(self):\n        for ball in self.balls:\n            if ball.y < self.width:\n                ball.update()\n            elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:\n                ball.fall()\n            elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:\n                self.fallen[ball.x] += 1\n            else:\n                pass\n                \n    def balls_on_board(self):\n        return len(self.balls) - sum(self.fallen)\n                \n    def add_ball(self):\n        if(len(self.balls) <= self.N):\n            self.balls.append(Ball())\n\n    def print_board(self):\n        for y in range(self.width + 1):\n            for x in range(y):\n                print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, \"\n    def print_ball(self, ball):\n        if ball.y <= self.width:\n            x = self.width - ball.y + 2*ball.x + self.shift\n        else:\n            x = 2*ball.x + self.shift\n        y = ball.y + 1\n        print_there(y, x, \"*\")\n         \n    def print_all(self):\n        print(chr(27) + \"[2J\")\n        self.print_board();\n        for ball in self.balls:\n            self.print_ball(ball)\n\n\ndef main():\n    board = Board(width = 15, well_depth = 5, N = 10)\n    board.add_ball() \n    while(board.balls_on_board() > 0):\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.add_ball()\n\n\nif __name__==\"__main__\":\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst boxW = 41      \nconst boxH = 37      \nconst pinsBaseW = 19 \nconst nMaxBalls = 55 \n\nconst centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1\n\nconst (\n    empty  = ' '\n    ball   = 'o'\n    wall   = '|'\n    corner = '+'\n    floor  = '-'\n    pin    = '.'\n)\n\ntype Ball struct{ x, y int }\n\nfunc newBall(x, y int) *Ball {\n    if box[y][x] != empty {\n        panic(\"Tried to create a new ball in a non-empty cell. Program terminated.\")\n    }\n    b := Ball{x, y}\n    box[y][x] = ball\n    return &b\n}\n\nfunc (b *Ball) doStep() {\n    if b.y <= 0 {\n        return \n    }\n    cell := box[b.y-1][b.x]\n    switch cell {\n    case empty:\n        box[b.y][b.x] = empty\n        b.y--\n        box[b.y][b.x] = ball\n    case pin:\n        box[b.y][b.x] = empty\n        b.y--\n        if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty {\n            b.x += rand.Intn(2)*2 - 1\n            box[b.y][b.x] = ball\n            return\n        } else if box[b.y][b.x-1] == empty {\n            b.x++\n        } else {\n            b.x--\n        }\n        box[b.y][b.x] = ball\n    default:\n        \n    }\n}\n\ntype Cell = byte\n\n\nvar box [boxH][boxW]Cell\n\nfunc initializeBox() {\n    \n    box[0][0] = corner\n    box[0][boxW-1] = corner\n    for i := 1; i < boxW-1; i++ {\n        box[0][i] = floor\n    }\n    for i := 0; i < boxW; i++ {\n        box[boxH-1][i] = box[0][i]\n    }\n\n    \n    for r := 1; r < boxH-1; r++ {\n        box[r][0] = wall\n        box[r][boxW-1] = wall\n    }\n\n    \n    for i := 1; i < boxH-1; i++ {\n        for j := 1; j < boxW-1; j++ {\n            box[i][j] = empty\n        }\n    }\n\n    \n    for nPins := 1; nPins <= pinsBaseW; nPins++ {\n        for p := 0; p < nPins; p++ {\n            box[boxH-2-nPins][centerH+1-nPins+p*2] = pin\n        }\n    }\n}\n\nfunc drawBox() {\n    for r := boxH - 1; r >= 0; r-- {\n        for c := 0; c < boxW; c++ {\n            fmt.Printf(\"%c\", box[r][c])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initializeBox()\n    var balls []*Ball\n    for i := 0; i < nMaxBalls+boxH; i++ {\n        fmt.Println(\"\\nStep\", i, \":\")\n        if i < nMaxBalls {\n            balls = append(balls, newBall(centerH, boxH-2)) \n        }\n        drawBox()\n\n        \n        \n        for _, b := range balls {\n            b.doStep()\n        }\n    }\n}\n"}
{"id": 44592, "name": "Galton box animation", "Python": "\n\nimport sys, os\nimport random\nimport time\n\ndef print_there(x, y, text):\n     sys.stdout.write(\"\\x1b7\\x1b[%d;%df%s\\x1b8\" % (x, y, text))\n     sys.stdout.flush()\n\n\nclass Ball():\n    def __init__(self):\n        self.x = 0\n        self.y = 0\n        \n    def update(self):\n        self.x += random.randint(0,1)\n        self.y += 1\n\n    def fall(self):\n        self.y +=1\n\n\nclass Board():\n    def __init__(self, width, well_depth, N):\n        self.balls = []\n        self.fallen = [0] * (width + 1)\n        self.width = width\n        self.well_depth = well_depth\n        self.N = N\n        self.shift = 4\n        \n    def update(self):\n        for ball in self.balls:\n            if ball.y < self.width:\n                ball.update()\n            elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:\n                ball.fall()\n            elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:\n                self.fallen[ball.x] += 1\n            else:\n                pass\n                \n    def balls_on_board(self):\n        return len(self.balls) - sum(self.fallen)\n                \n    def add_ball(self):\n        if(len(self.balls) <= self.N):\n            self.balls.append(Ball())\n\n    def print_board(self):\n        for y in range(self.width + 1):\n            for x in range(y):\n                print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, \"\n    def print_ball(self, ball):\n        if ball.y <= self.width:\n            x = self.width - ball.y + 2*ball.x + self.shift\n        else:\n            x = 2*ball.x + self.shift\n        y = ball.y + 1\n        print_there(y, x, \"*\")\n         \n    def print_all(self):\n        print(chr(27) + \"[2J\")\n        self.print_board();\n        for ball in self.balls:\n            self.print_ball(ball)\n\n\ndef main():\n    board = Board(width = 15, well_depth = 5, N = 10)\n    board.add_ball() \n    while(board.balls_on_board() > 0):\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.print_all()\n         time.sleep(0.25)\n         board.update()\n         board.add_ball()\n\n\nif __name__==\"__main__\":\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nconst boxW = 41      \nconst boxH = 37      \nconst pinsBaseW = 19 \nconst nMaxBalls = 55 \n\nconst centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1\n\nconst (\n    empty  = ' '\n    ball   = 'o'\n    wall   = '|'\n    corner = '+'\n    floor  = '-'\n    pin    = '.'\n)\n\ntype Ball struct{ x, y int }\n\nfunc newBall(x, y int) *Ball {\n    if box[y][x] != empty {\n        panic(\"Tried to create a new ball in a non-empty cell. Program terminated.\")\n    }\n    b := Ball{x, y}\n    box[y][x] = ball\n    return &b\n}\n\nfunc (b *Ball) doStep() {\n    if b.y <= 0 {\n        return \n    }\n    cell := box[b.y-1][b.x]\n    switch cell {\n    case empty:\n        box[b.y][b.x] = empty\n        b.y--\n        box[b.y][b.x] = ball\n    case pin:\n        box[b.y][b.x] = empty\n        b.y--\n        if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty {\n            b.x += rand.Intn(2)*2 - 1\n            box[b.y][b.x] = ball\n            return\n        } else if box[b.y][b.x-1] == empty {\n            b.x++\n        } else {\n            b.x--\n        }\n        box[b.y][b.x] = ball\n    default:\n        \n    }\n}\n\ntype Cell = byte\n\n\nvar box [boxH][boxW]Cell\n\nfunc initializeBox() {\n    \n    box[0][0] = corner\n    box[0][boxW-1] = corner\n    for i := 1; i < boxW-1; i++ {\n        box[0][i] = floor\n    }\n    for i := 0; i < boxW; i++ {\n        box[boxH-1][i] = box[0][i]\n    }\n\n    \n    for r := 1; r < boxH-1; r++ {\n        box[r][0] = wall\n        box[r][boxW-1] = wall\n    }\n\n    \n    for i := 1; i < boxH-1; i++ {\n        for j := 1; j < boxW-1; j++ {\n            box[i][j] = empty\n        }\n    }\n\n    \n    for nPins := 1; nPins <= pinsBaseW; nPins++ {\n        for p := 0; p < nPins; p++ {\n            box[boxH-2-nPins][centerH+1-nPins+p*2] = pin\n        }\n    }\n}\n\nfunc drawBox() {\n    for r := boxH - 1; r >= 0; r-- {\n        for c := 0; c < boxW; c++ {\n            fmt.Printf(\"%c\", box[r][c])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    initializeBox()\n    var balls []*Ball\n    for i := 0; i < nMaxBalls+boxH; i++ {\n        fmt.Println(\"\\nStep\", i, \":\")\n        if i < nMaxBalls {\n            balls = append(balls, newBall(centerH, boxH-2)) \n        }\n        drawBox()\n\n        \n        \n        for _, b := range balls {\n            b.doStep()\n        }\n    }\n}\n"}
{"id": 44593, "name": "Sorting Algorithms_Circle Sort", "Python": "\n\n\n\n\ndef circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':\n    \n    n = R-L\n    if n < 2:\n        return 0\n    swaps = 0\n    m = n//2\n    for i in range(m):\n        if A[R-(i+1)] < A[L+i]:\n            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)\n            swaps += 1\n    if (n & 1) and (A[L+m] < A[L+m-1]):\n        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)\n        swaps += 1\n    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)\n\ndef circle_sort(L:list)->'sort A in place, returning the number of swaps':\n    swaps = 0\n    s = 1\n    while s:\n        s = circle_sort_backend(L, 0, len(L))\n        swaps += s\n    return swaps\n\n\nif __name__ == '__main__':\n    from random import shuffle\n    for i in range(309):\n        L = list(range(i))\n        M = L[:]\n        shuffle(L)\n        N = L[:]\n        circle_sort(L)\n        if L != M:\n            print(len(L))\n            print(N)\n            print(L)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc circleSort(a []int, lo, hi, swaps int) int {\n    if lo == hi {\n        return swaps\n    }\n    high, low := hi, lo\n    mid := (hi - lo) / 2\n    for lo < hi {\n        if a[lo] > a[hi] {\n            a[lo], a[hi] = a[hi], a[lo]\n            swaps++\n        }\n        lo++\n        hi--\n    }\n    if lo == hi {\n        if a[lo] > a[hi+1] {\n            a[lo], a[hi+1] = a[hi+1], a[lo]\n            swaps++\n        }\n    }\n    swaps = circleSort(a, low, low+mid, swaps)\n    swaps = circleSort(a, low+mid+1, high, swaps)\n    return swaps\n}\n\nfunc main() {\n    aa := [][]int{\n        {6, 7, 8, 9, 2, 5, 3, 4, 1},\n        {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},\n    }\n    for _, a := range aa {\n        fmt.Printf(\"Original: %v\\n\", a)\n        for circleSort(a, 0, len(a)-1, 0) != 0 {\n            \n        }\n        fmt.Printf(\"Sorted  : %v\\n\\n\", a)\n    }\n}\n"}
{"id": 44594, "name": "Sorting Algorithms_Circle Sort", "Python": "\n\n\n\n\ndef circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':\n    \n    n = R-L\n    if n < 2:\n        return 0\n    swaps = 0\n    m = n//2\n    for i in range(m):\n        if A[R-(i+1)] < A[L+i]:\n            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)\n            swaps += 1\n    if (n & 1) and (A[L+m] < A[L+m-1]):\n        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)\n        swaps += 1\n    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)\n\ndef circle_sort(L:list)->'sort A in place, returning the number of swaps':\n    swaps = 0\n    s = 1\n    while s:\n        s = circle_sort_backend(L, 0, len(L))\n        swaps += s\n    return swaps\n\n\nif __name__ == '__main__':\n    from random import shuffle\n    for i in range(309):\n        L = list(range(i))\n        M = L[:]\n        shuffle(L)\n        N = L[:]\n        circle_sort(L)\n        if L != M:\n            print(len(L))\n            print(N)\n            print(L)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc circleSort(a []int, lo, hi, swaps int) int {\n    if lo == hi {\n        return swaps\n    }\n    high, low := hi, lo\n    mid := (hi - lo) / 2\n    for lo < hi {\n        if a[lo] > a[hi] {\n            a[lo], a[hi] = a[hi], a[lo]\n            swaps++\n        }\n        lo++\n        hi--\n    }\n    if lo == hi {\n        if a[lo] > a[hi+1] {\n            a[lo], a[hi+1] = a[hi+1], a[lo]\n            swaps++\n        }\n    }\n    swaps = circleSort(a, low, low+mid, swaps)\n    swaps = circleSort(a, low+mid+1, high, swaps)\n    return swaps\n}\n\nfunc main() {\n    aa := [][]int{\n        {6, 7, 8, 9, 2, 5, 3, 4, 1},\n        {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},\n    }\n    for _, a := range aa {\n        fmt.Printf(\"Original: %v\\n\", a)\n        for circleSort(a, 0, len(a)-1, 0) != 0 {\n            \n        }\n        fmt.Printf(\"Sorted  : %v\\n\\n\", a)\n    }\n}\n"}
{"id": 44595, "name": "Kronecker product based fractals", "Python": "import os\nfrom PIL import Image\n\n\ndef imgsave(path, arr):\n    w, h = len(arr), len(arr[0])\n    img = Image.new('1', (w, h))\n    for x in range(w):\n        for y in range(h):\n            img.putpixel((x, y), arr[x][y])\n    img.save(path)\n\n\ndef get_shape(mat):\n    return len(mat), len(mat[0])\n\n\ndef kron(matrix1, matrix2):\n    \n    final_list = []\n\n    count = len(matrix2)\n\n    for elem1 in matrix1:\n        for i in range(count):\n            sub_list = []\n            for num1 in elem1:\n                for num2 in matrix2[i]:\n                    sub_list.append(num1 * num2)\n            final_list.append(sub_list)\n\n    return final_list\n\n\ndef kronpow(mat):\n    \n    matrix = mat\n    while True:\n        yield matrix\n        matrix = kron(mat, matrix)\n\n\ndef fractal(name, mat, order=6):\n    \n    path = os.path.join('fractals', name)\n    os.makedirs(path, exist_ok=True)\n\n    fgen = kronpow(mat)\n    print(name)\n    for i in range(order):\n        p = os.path.join(path, f'{i}.jpg')\n        print('Calculating n =', i, end='\\t', flush=True)\n\n        mat = next(fgen)\n        imgsave(p, mat)\n\n        x, y = get_shape(mat)\n        print('Saved as', x, 'x', y, 'image', p)\n\n\ntest1 = [\n    [0, 1, 0],\n    [1, 1, 1],\n    [0, 1, 0]\n]\n\ntest2 = [\n    [1, 1, 1],\n    [1, 0, 1],\n    [1, 1, 1]\n]\n\ntest3 = [\n    [1, 0, 1],\n    [0, 1, 0],\n    [1, 0, 1]\n]\n\nfractal('test1', test1)\nfractal('test2', test2)\nfractal('test3', test3)\n", "Go": "package main\n\nimport \"fmt\"\n\ntype matrix [][]int\n\nfunc (m1 matrix) kroneckerProduct(m2 matrix) matrix {\n    m := len(m1)\n    n := len(m1[0])\n    p := len(m2)\n    q := len(m2[0])\n    rtn := m * p\n    ctn := n * q\n    r := make(matrix, rtn)\n    for i := range r {\n        r[i] = make([]int, ctn) \n    }\n    for i := 0; i < m; i++ {\n        for j := 0; j < n; j++ {\n            for k := 0; k < p; k++ {\n                for l := 0; l < q; l++ {\n                    r[p*i+k][q*j+l] = m1[i][j] * m2[k][l]\n                }\n            }\n        }\n    }\n    return r\n}\n\nfunc (m matrix) kroneckerPower(n int) matrix {\n    pow := m\n    for i := 1; i < n; i++ {\n        pow = pow.kroneckerProduct(m)\n    }\n    return pow\n}\n\nfunc (m matrix) print(text string) {\n    fmt.Println(text, \"fractal :\\n\")\n    for i := range m {\n        for j := range m[0] {\n            if m[i][j] == 1 {\n                fmt.Print(\"*\")\n            } else {\n                fmt.Print(\" \")\n            }\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}\n    m1.kroneckerPower(4).print(\"Vivsek\")\n\n    m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}\n    m2.kroneckerPower(4).print(\"Sierpinski carpet\")\n}\n"}
{"id": 44596, "name": "Read a configuration file", "Python": "def readconf(fn):\n    ret = {}\n    with file(fn) as fp:\n        for line in fp:\n            \n            line = line.strip()\n            if not line or line.startswith('\n            \n            boolval = True\n            \n            if line.startswith(';'):\n                \n                line = line.lstrip(';')\n                \n                if len(line.split()) != 1: continue\n                boolval = False\n            \n            bits = line.split(None, 1)\n            if len(bits) == 1:\n                \n                k = bits[0]\n                v = boolval\n            else:\n                \n                k, v = bits\n            ret[k.lower()] = v\n    return ret\n\n\nif __name__ == '__main__':\n    import sys\n    conf = readconf(sys.argv[1])\n    for k, v in sorted(conf.items()):\n        print k, '=', v\n", "Go": "package config\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"strings\"\n\t\"io/ioutil\"\n)\n\nvar (\n\tENONE    = errors.New(\"Requested value does not exist\")\n\tEBADTYPE = errors.New(\"Requested type and actual type do not match\")\n\tEBADVAL  = errors.New(\"Value and type do not match\")\n)\n\ntype varError struct {\n\terr error\n\tn   string\n\tt   VarType\n}\n\nfunc (err *varError) Error() string {\n\treturn fmt.Sprintf(\"%v: (%q, %v)\", err.err, err.n, err.t)\n}\n\ntype VarType int\n\nconst (\n\tBool VarType = 1 + iota\n\tArray\n\tString\n)\n\nfunc (t VarType) String() string {\n\tswitch t {\n\tcase Bool:\n\t\treturn \"Bool\"\n\tcase Array:\n\t\treturn \"Array\"\n\tcase String:\n\t\treturn \"String\"\n\t}\n\n\tpanic(\"Unknown VarType\")\n}\n\ntype confvar struct {\n\tType VarType\n\tVal  interface{}\n}\n\ntype Config struct {\n\tm map[string]confvar\n}\n\nfunc Parse(r io.Reader) (c *Config, err error) {\n\tc = new(Config)\n\tc.m = make(map[string]confvar)\n\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlines := bytes.Split(buf, []byte{'\\n'})\n\n\tfor _, line := range lines {\n\t\tline = bytes.TrimSpace(line)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch line[0] {\n\t\tcase '#', ';':\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := bytes.SplitN(line, []byte{' '}, 2)\n\t\tnam := string(bytes.ToLower(parts[0]))\n\n\t\tif len(parts) == 1 {\n\t\t\tc.m[nam] = confvar{Bool, true}\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(string(parts[1]), \",\") {\n\t\t\ttmpB := bytes.Split(parts[1], []byte{','})\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpB[i] = bytes.TrimSpace(tmpB[i])\n\t\t\t}\n\t\t\ttmpS := make([]string, 0, len(tmpB))\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpS = append(tmpS, string(tmpB[i]))\n\t\t\t}\n\n\t\t\tc.m[nam] = confvar{Array, tmpS}\n\t\t\tcontinue\n\t\t}\n\n\t\tc.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))}\n\t}\n\n\treturn\n}\n\nfunc (c *Config) Bool(name string) (bool, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn false, nil\n\t}\n\n\tif c.m[name].Type != Bool {\n\t\treturn false, &varError{EBADTYPE, name, Bool}\n\t}\n\n\tv, ok := c.m[name].Val.(bool)\n\tif !ok {\n\t\treturn false, &varError{EBADVAL, name, Bool}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) Array(name string) ([]string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn nil, &varError{ENONE, name, Array}\n\t}\n\n\tif c.m[name].Type != Array {\n\t\treturn nil, &varError{EBADTYPE, name, Array}\n\t}\n\n\tv, ok := c.m[name].Val.([]string)\n\tif !ok {\n\t\treturn nil, &varError{EBADVAL, name, Array}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) String(name string) (string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn \"\", &varError{ENONE, name, String}\n\t}\n\n\tif c.m[name].Type != String {\n\t\treturn \"\", &varError{EBADTYPE, name, String}\n\t}\n\n\tv, ok := c.m[name].Val.(string)\n\tif !ok {\n\t\treturn \"\", &varError{EBADVAL, name, String}\n\t}\n\n\treturn v, nil\n}\n"}
{"id": 44597, "name": "Read a configuration file", "Python": "def readconf(fn):\n    ret = {}\n    with file(fn) as fp:\n        for line in fp:\n            \n            line = line.strip()\n            if not line or line.startswith('\n            \n            boolval = True\n            \n            if line.startswith(';'):\n                \n                line = line.lstrip(';')\n                \n                if len(line.split()) != 1: continue\n                boolval = False\n            \n            bits = line.split(None, 1)\n            if len(bits) == 1:\n                \n                k = bits[0]\n                v = boolval\n            else:\n                \n                k, v = bits\n            ret[k.lower()] = v\n    return ret\n\n\nif __name__ == '__main__':\n    import sys\n    conf = readconf(sys.argv[1])\n    for k, v in sorted(conf.items()):\n        print k, '=', v\n", "Go": "package config\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"strings\"\n\t\"io/ioutil\"\n)\n\nvar (\n\tENONE    = errors.New(\"Requested value does not exist\")\n\tEBADTYPE = errors.New(\"Requested type and actual type do not match\")\n\tEBADVAL  = errors.New(\"Value and type do not match\")\n)\n\ntype varError struct {\n\terr error\n\tn   string\n\tt   VarType\n}\n\nfunc (err *varError) Error() string {\n\treturn fmt.Sprintf(\"%v: (%q, %v)\", err.err, err.n, err.t)\n}\n\ntype VarType int\n\nconst (\n\tBool VarType = 1 + iota\n\tArray\n\tString\n)\n\nfunc (t VarType) String() string {\n\tswitch t {\n\tcase Bool:\n\t\treturn \"Bool\"\n\tcase Array:\n\t\treturn \"Array\"\n\tcase String:\n\t\treturn \"String\"\n\t}\n\n\tpanic(\"Unknown VarType\")\n}\n\ntype confvar struct {\n\tType VarType\n\tVal  interface{}\n}\n\ntype Config struct {\n\tm map[string]confvar\n}\n\nfunc Parse(r io.Reader) (c *Config, err error) {\n\tc = new(Config)\n\tc.m = make(map[string]confvar)\n\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlines := bytes.Split(buf, []byte{'\\n'})\n\n\tfor _, line := range lines {\n\t\tline = bytes.TrimSpace(line)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch line[0] {\n\t\tcase '#', ';':\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := bytes.SplitN(line, []byte{' '}, 2)\n\t\tnam := string(bytes.ToLower(parts[0]))\n\n\t\tif len(parts) == 1 {\n\t\t\tc.m[nam] = confvar{Bool, true}\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(string(parts[1]), \",\") {\n\t\t\ttmpB := bytes.Split(parts[1], []byte{','})\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpB[i] = bytes.TrimSpace(tmpB[i])\n\t\t\t}\n\t\t\ttmpS := make([]string, 0, len(tmpB))\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpS = append(tmpS, string(tmpB[i]))\n\t\t\t}\n\n\t\t\tc.m[nam] = confvar{Array, tmpS}\n\t\t\tcontinue\n\t\t}\n\n\t\tc.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))}\n\t}\n\n\treturn\n}\n\nfunc (c *Config) Bool(name string) (bool, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn false, nil\n\t}\n\n\tif c.m[name].Type != Bool {\n\t\treturn false, &varError{EBADTYPE, name, Bool}\n\t}\n\n\tv, ok := c.m[name].Val.(bool)\n\tif !ok {\n\t\treturn false, &varError{EBADVAL, name, Bool}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) Array(name string) ([]string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn nil, &varError{ENONE, name, Array}\n\t}\n\n\tif c.m[name].Type != Array {\n\t\treturn nil, &varError{EBADTYPE, name, Array}\n\t}\n\n\tv, ok := c.m[name].Val.([]string)\n\tif !ok {\n\t\treturn nil, &varError{EBADVAL, name, Array}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) String(name string) (string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn \"\", &varError{ENONE, name, String}\n\t}\n\n\tif c.m[name].Type != String {\n\t\treturn \"\", &varError{EBADTYPE, name, String}\n\t}\n\n\tv, ok := c.m[name].Val.(string)\n\tif !ok {\n\t\treturn \"\", &varError{EBADVAL, name, String}\n\t}\n\n\treturn v, nil\n}\n"}
{"id": 44598, "name": "Sort using a custom comparator", "Python": "strings = \"here are Some sample strings to be sorted\".split()\n\ndef mykey(x):\n    return -len(x), x.upper()\n\nprint sorted(strings, key=mykey)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\ntype sortable []string\n\nfunc (s sortable) Len() int      { return len(s) }\nfunc (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s sortable) Less(i, j int) bool {\n    a, b := s[i], s[j]\n    if len(a) != len(b) {\n        return len(a) > len(b)\n    }\n    return strings.ToLower(a) < strings.ToLower(b)\n}\n\nfunc main() {\n    var s sortable = strings.Fields(\"To tell your name the livelong day To an admiring bog\")\n    fmt.Println(s, \"(original)\")\n\n    sort.Sort(s)\n    fmt.Println(s, \"(sorted)\")\n}\n"}
{"id": 44599, "name": "Circular primes", "Python": "import random\n\ndef is_Prime(n):\n    \n    if n!=int(n):\n        return False\n    n=int(n)\n    \n    if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:\n        return False\n\n    if n==2 or n==3 or n==5 or n==7:\n        return True\n    s = 0\n    d = n-1\n    while d%2==0:\n        d>>=1\n        s+=1\n    assert(2**s * d == n-1)\n\n    def trial_composite(a):\n        if pow(a, d, n) == 1:\n            return False\n        for i in range(s):\n            if pow(a, 2**i * d, n) == n-1:\n                return False\n        return True\n\n    for i in range(8):\n        a = random.randrange(2, n)\n        if trial_composite(a):\n            return False\n\n    return True\n\ndef isPrime(n: int) -> bool:\n    \n    \n    if (n <= 1) :\n        return False\n    if (n <= 3) :\n        return True\n    \n    \n    if (n % 2 == 0 or n % 3 == 0) :\n        return False\n    i = 5\n    while(i * i <= n) :\n        if (n % i == 0 or n % (i + 2) == 0) :\n            return False\n        i = i + 6\n    return True\n\ndef rotations(n: int)-> set((int,)):\n    \n    a = str(n)\n    return set(int(a[i:] + a[:i]) for i in range(len(a)))\n\ndef isCircular(n: int) -> bool:\n    \n    return all(isPrime(int(o)) for o in rotations(n))\n\nfrom itertools import product\n\ndef main():\n    result = [2, 3, 5, 7]\n    first = '137'\n    latter = '1379'\n    for i in range(1, 6):\n        s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))\n        while s:\n            a = s.pop()\n            b = rotations(a)\n            if isCircular(a):\n                result.append(min(b))\n            s -= b\n    result.sort()\n    return result\n\nassert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()\n\n\nrepunit = lambda n: int('1' * n)\n\ndef repmain(n: int) -> list:\n    \n    result = []\n    i = 2\n    while len(result) < n:\n        if is_Prime(repunit(i)):\n            result.append(i)\n        i += 1\n    return result\n\nassert [2, 19, 23, 317, 1031] == repmain(5)\n\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    big \"github.com/ncw/gmp\"\n    \"strings\"\n)\n\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc repunit(n int) *big.Int {\n    ones := strings.Repeat(\"1\", n)\n    b, _ := new(big.Int).SetString(ones, 10)\n    return b\n}\n\nvar circs = []int{}\n\n\nfunc alreadyFound(n int) bool {\n    for _, i := range circs {\n        if i == n {\n            return true\n        }\n    }\n    return false\n}\n\nfunc isCircular(n int) bool {\n    nn := n\n    pow := 1 \n    for nn > 0 {\n        pow *= 10\n        nn /= 10\n    }\n    nn = n\n    for {\n        nn *= 10\n        f := nn / pow \n        nn += f * (1 - pow)\n        if alreadyFound(nn) {\n            return false\n        }\n        if nn == n {\n            break\n        }\n        if !isPrime(nn) {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    fmt.Println(\"The first 19 circular primes are:\")\n    digits := [4]int{1, 3, 7, 9}\n    q := []int{1, 2, 3, 5, 7, 9}  \n    fq := []int{1, 2, 3, 5, 7, 9} \n    count := 0\n    for {\n        f := q[0]   \n        fd := fq[0] \n        if isPrime(f) && isCircular(f) {\n            circs = append(circs, f)\n            count++\n            if count == 19 {\n                break\n            }\n        }\n        copy(q, q[1:])   \n        q = q[:len(q)-1] \n        copy(fq, fq[1:]) \n        fq = fq[:len(fq)-1]\n        if f == 2 || f == 5 { \n            continue\n        }\n        \n        \n        for _, d := range digits {\n            if d >= fd {\n                q = append(q, f*10+d)\n                fq = append(fq, fd)\n            }\n        }\n    }\n    fmt.Println(circs)\n    fmt.Println(\"\\nThe next 4 circular primes, in repunit format, are:\")\n    count = 0\n    var rus []string\n    for i := 7; count < 4; i++ {\n        if repunit(i).ProbablyPrime(10) {\n            count++\n            rus = append(rus, fmt.Sprintf(\"R(%d)\", i))\n        }\n    }\n    fmt.Println(rus)\n    fmt.Println(\"\\nThe following repunits are probably circular primes:\")\n    for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} {\n        fmt.Printf(\"R(%-5d) : %t\\n\", i, repunit(i).ProbablyPrime(10))\n    }\n}\n"}
{"id": 44600, "name": "Animation", "Python": "txt = \"Hello, world! \"\nleft = True\n\ndef draw():\n    global txt\n    background(128)\n    text(txt, 10, height / 2)\n    if frameCount % 10 == 0:\n        if (left):\n            txt = rotate(txt, 1)\n        else:\n            txt = rotate(txt, -1)\n        println(txt)\n\ndef mouseReleased():\n    global left\n    left = not left\n\ndef rotate(text, startIdx):\n    rotated = text[startIdx:] + text[:startIdx]\n    return rotated\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"time\"\n\n    \"github.com/gdamore/tcell\"\n)\n\nconst (\n    msg             = \"Hello World! \"\n    x0, y0          = 8, 3\n    shiftsPerSecond = 4\n    clicksToExit    = 5\n)\n\nfunc main() {\n    s, err := tcell.NewScreen()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = s.Init(); err != nil {\n        log.Fatal(err)\n    }\n    s.Clear()\n    s.EnableMouse()\n    tick := time.Tick(time.Second / shiftsPerSecond)\n    click := make(chan bool)\n    go func() {\n        for {\n            em, ok := s.PollEvent().(*tcell.EventMouse)\n            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {\n                continue\n            }\n            mx, my := em.Position()\n            if my == y0 && mx >= x0 && mx < x0+len(msg) {\n                click <- true\n            }\n        }\n    }()\n    for inc, shift, clicks := 1, 0, 0; ; {\n        select {\n        case <-tick:\n            shift = (shift + inc) % len(msg)\n            for i, r := range msg {\n                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)\n            }\n            s.Show()\n        case <-click:\n            clicks++\n            if clicks == clicksToExit {\n                s.Fini()\n                return\n            }\n            inc = len(msg) - inc\n        }\n    }\n}\n"}
{"id": 44601, "name": "Animation", "Python": "txt = \"Hello, world! \"\nleft = True\n\ndef draw():\n    global txt\n    background(128)\n    text(txt, 10, height / 2)\n    if frameCount % 10 == 0:\n        if (left):\n            txt = rotate(txt, 1)\n        else:\n            txt = rotate(txt, -1)\n        println(txt)\n\ndef mouseReleased():\n    global left\n    left = not left\n\ndef rotate(text, startIdx):\n    rotated = text[startIdx:] + text[:startIdx]\n    return rotated\n", "Go": "package main\n\nimport (\n    \"log\"\n    \"time\"\n\n    \"github.com/gdamore/tcell\"\n)\n\nconst (\n    msg             = \"Hello World! \"\n    x0, y0          = 8, 3\n    shiftsPerSecond = 4\n    clicksToExit    = 5\n)\n\nfunc main() {\n    s, err := tcell.NewScreen()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = s.Init(); err != nil {\n        log.Fatal(err)\n    }\n    s.Clear()\n    s.EnableMouse()\n    tick := time.Tick(time.Second / shiftsPerSecond)\n    click := make(chan bool)\n    go func() {\n        for {\n            em, ok := s.PollEvent().(*tcell.EventMouse)\n            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {\n                continue\n            }\n            mx, my := em.Position()\n            if my == y0 && mx >= x0 && mx < x0+len(msg) {\n                click <- true\n            }\n        }\n    }()\n    for inc, shift, clicks := 1, 0, 0; ; {\n        select {\n        case <-tick:\n            shift = (shift + inc) % len(msg)\n            for i, r := range msg {\n                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)\n            }\n            s.Show()\n        case <-click:\n            clicks++\n            if clicks == clicksToExit {\n                s.Fini()\n                return\n            }\n            inc = len(msg) - inc\n        }\n    }\n}\n"}
{"id": 44602, "name": "Sorting algorithms_Radix sort", "Python": "\nfrom math import log\n \ndef getDigit(num, base, digit_num):\n    \n    return (num // base ** digit_num) % base  \n \ndef makeBlanks(size):\n    \n    return [ [] for i in range(size) ]  \n \ndef split(a_list, base, digit_num):\n    buckets = makeBlanks(base)\n    for num in a_list:\n        \n        buckets[getDigit(num, base, digit_num)].append(num)  \n    return buckets\n \n\ndef merge(a_list):\n    new_list = []\n    for sublist in a_list:\n       new_list.extend(sublist)\n    return new_list\n \ndef maxAbs(a_list):\n    \n    return max(abs(num) for num in a_list)\n\ndef split_by_sign(a_list):\n    \n    \n    buckets = [[], []]\n    for num in a_list:\n        if num < 0:\n            buckets[0].append(num)\n        else:\n            buckets[1].append(num)\n    return buckets\n \ndef radixSort(a_list, base):\n    \n    passes = int(round(log(maxAbs(a_list), base)) + 1) \n    new_list = list(a_list)\n    for digit_num in range(passes):\n        new_list = merge(split(new_list, base, digit_num))\n    return merge(split_by_sign(new_list))\n", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/binary\"\n    \"fmt\"\n)\n\n\ntype word int32\nconst wordLen = 4\nconst highBit = -1 << 31\n\nvar data = []word{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    buf := bytes.NewBuffer(nil)\n    ds := make([][]byte, len(data))\n    for i, x := range data {\n        binary.Write(buf, binary.LittleEndian, x^highBit)\n        b := make([]byte, wordLen)\n        buf.Read(b)\n        ds[i] = b\n    }\n    bins := make([][][]byte, 256)\n    for i := 0; i < wordLen; i++ {\n        for _, b := range ds {\n            bins[b[i]] = append(bins[b[i]], b)\n        }\n        j := 0\n        for k, bs := range bins {\n            copy(ds[j:], bs)\n            j += len(bs)\n            bins[k] = bs[:0]\n        }\n    }\n    fmt.Println(\"original:\", data)\n    var w word\n    for i, b := range ds {\n        buf.Write(b)\n        binary.Read(buf, binary.LittleEndian, &w)\n        data[i] = w^highBit\n    }\n    fmt.Println(\"sorted:  \", data)\n}\n"}
{"id": 44603, "name": "List comprehensions", "Python": "[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]\n", "Go": "package main\n\nimport \"fmt\"\n\ntype (\n    seq  []int\n    sofs []seq\n)\n\nfunc newSeq(start, end int) seq {\n    if end < start {\n        end = start\n    }\n    s := make(seq, end-start+1)\n    for i := 0; i < len(s); i++ {\n        s[i] = start + i\n    }\n    return s\n}\n\nfunc newSofs() sofs {\n    return sofs{seq{}}\n}\n\nfunc (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {\n    var s2 sofs\n    for _, t := range expr(s, in) {\n        if pred(t) {\n            s2 = append(s2, t)\n        }\n    }\n    return s2\n}\n\nfunc (s sofs) build(t seq) sofs {\n    var u sofs\n    for _, ss := range s {\n        for _, tt := range t {\n            uu := make(seq, len(ss))\n            copy(uu, ss)\n            uu = append(uu, tt)\n            u = append(u, uu)\n        }\n    }\n    return u\n}\n\nfunc main() {\n    pt := newSofs()\n    in := newSeq(1, 20)\n    expr := func(s sofs, t seq) sofs {\n        return s.build(t).build(t).build(t)\n    }\n    pred := func(t seq) bool {\n        if len(t) != 3 {\n            return false\n        }\n        return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]\n    }\n    pt = pt.listComp(in, expr, pred)\n    fmt.Println(pt)\n}\n"}
{"id": 44604, "name": "Sorting algorithms_Selection sort", "Python": "def selection_sort(lst):\n    for i, e in enumerate(lst):\n        mn = min(range(i,len(lst)), key=lst.__getitem__)\n        lst[i], lst[mn] = lst[mn], e\n    return lst\n", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    selectionSort(a)\n    fmt.Println(\"after: \", a)\n}\n\nfunc selectionSort(a []int) {\n    last := len(a) - 1\n    for i := 0; i < last; i++ {\n        aMin := a[i]\n        iMin := i\n        for j := i + 1; j < len(a); j++ {\n            if a[j] < aMin {\n                aMin = a[j]\n                iMin = j\n            }\n        }\n        a[i], a[iMin] = aMin, a[i]\n    }\n}\n"}
{"id": 44605, "name": "Jacobi symbol", "Python": "def jacobi(a, n):\n    if n <= 0:\n        raise ValueError(\"'n' must be a positive integer.\")\n    if n % 2 == 0:\n        raise ValueError(\"'n' must be odd.\")\n    a %= n\n    result = 1\n    while a != 0:\n        while a % 2 == 0:\n            a /= 2\n            n_mod_8 = n % 8\n            if n_mod_8 in (3, 5):\n                result = -result\n        a, n = n, a\n        if a % 4 == 3 and n % 4 == 3:\n            result = -result\n        a %= n\n    if n == 1:\n        return result\n    else:\n        return 0\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n)\n\nfunc jacobi(a, n uint64) int {\n    if n%2 == 0 {\n        log.Fatal(\"'n' must be a positive odd integer\")\n    }\n    a %= n\n    result := 1\n    for a != 0 {\n        for a%2 == 0 {\n            a /= 2\n            nn := n % 8\n            if nn == 3 || nn == 5 {\n                result = -result\n            }\n        }\n        a, n = n, a\n        if a%4 == 3 && n%4 == 3 {\n            result = -result\n        }\n        a %= n\n    }\n    if n == 1 {\n        return result\n    }\n    return 0\n}\n\nfunc main() {\n    fmt.Println(\"Using hand-coded version:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            fmt.Printf(\" % d\", jacobi(a, n))\n        }\n        fmt.Println()\n    }\n\n    ba, bn := new(big.Int), new(big.Int)\n    fmt.Println(\"\\nUsing standard library function:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            ba.SetUint64(a)\n            bn.SetUint64(n)\n            fmt.Printf(\" % d\", big.Jacobi(ba, bn))            \n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 44606, "name": "Jacobi symbol", "Python": "def jacobi(a, n):\n    if n <= 0:\n        raise ValueError(\"'n' must be a positive integer.\")\n    if n % 2 == 0:\n        raise ValueError(\"'n' must be odd.\")\n    a %= n\n    result = 1\n    while a != 0:\n        while a % 2 == 0:\n            a /= 2\n            n_mod_8 = n % 8\n            if n_mod_8 in (3, 5):\n                result = -result\n        a, n = n, a\n        if a % 4 == 3 and n % 4 == 3:\n            result = -result\n        a %= n\n    if n == 1:\n        return result\n    else:\n        return 0\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math/big\"\n)\n\nfunc jacobi(a, n uint64) int {\n    if n%2 == 0 {\n        log.Fatal(\"'n' must be a positive odd integer\")\n    }\n    a %= n\n    result := 1\n    for a != 0 {\n        for a%2 == 0 {\n            a /= 2\n            nn := n % 8\n            if nn == 3 || nn == 5 {\n                result = -result\n            }\n        }\n        a, n = n, a\n        if a%4 == 3 && n%4 == 3 {\n            result = -result\n        }\n        a %= n\n    }\n    if n == 1 {\n        return result\n    }\n    return 0\n}\n\nfunc main() {\n    fmt.Println(\"Using hand-coded version:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            fmt.Printf(\" % d\", jacobi(a, n))\n        }\n        fmt.Println()\n    }\n\n    ba, bn := new(big.Int), new(big.Int)\n    fmt.Println(\"\\nUsing standard library function:\")\n    fmt.Println(\"n/a  0  1  2  3  4  5  6  7  8  9\")\n    fmt.Println(\"---------------------------------\")\n    for n := uint64(1); n <= 17; n += 2 {\n        fmt.Printf(\"%2d \", n)\n        for a := uint64(0); a <= 9; a++ {\n            ba.SetUint64(a)\n            bn.SetUint64(n)\n            fmt.Printf(\" % d\", big.Jacobi(ba, bn))            \n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 44607, "name": "K-d tree", "Python": "from random import seed, random\nfrom time import time\nfrom operator import itemgetter\nfrom collections import namedtuple\nfrom math import sqrt\nfrom copy import deepcopy\n\n\ndef sqd(p1, p2):\n    return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))\n\n\nclass KdNode(object):\n    __slots__ = (\"dom_elt\", \"split\", \"left\", \"right\")\n\n    def __init__(self, dom_elt, split, left, right):\n        self.dom_elt = dom_elt\n        self.split = split\n        self.left = left\n        self.right = right\n\n\nclass Orthotope(object):\n    __slots__ = (\"min\", \"max\")\n\n    def __init__(self, mi, ma):\n        self.min, self.max = mi, ma\n\n\nclass KdTree(object):\n    __slots__ = (\"n\", \"bounds\")\n\n    def __init__(self, pts, bounds):\n        def nk2(split, exset):\n            if not exset:\n                return None\n            exset.sort(key=itemgetter(split))\n            m = len(exset) // 2\n            d = exset[m]\n            while m + 1 < len(exset) and exset[m + 1][split] == d[split]:\n                m += 1\n            d = exset[m]\n\n\n            s2 = (split + 1) % len(d)  \n            return KdNode(d, split, nk2(s2, exset[:m]),\n                                    nk2(s2, exset[m + 1:]))\n        self.n = nk2(0, pts)\n        self.bounds = bounds\n\nT3 = namedtuple(\"T3\", \"nearest dist_sqd nodes_visited\")\n\n\ndef find_nearest(k, t, p):\n    def nn(kd, target, hr, max_dist_sqd):\n        if kd is None:\n            return T3([0.0] * k, float(\"inf\"), 0)\n\n        nodes_visited = 1\n        s = kd.split\n        pivot = kd.dom_elt\n        left_hr = deepcopy(hr)\n        right_hr = deepcopy(hr)\n        left_hr.max[s] = pivot[s]\n        right_hr.min[s] = pivot[s]\n\n        if target[s] <= pivot[s]:\n            nearer_kd, nearer_hr = kd.left, left_hr\n            further_kd, further_hr = kd.right, right_hr\n        else:\n            nearer_kd, nearer_hr = kd.right, right_hr\n            further_kd, further_hr = kd.left, left_hr\n\n        n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)\n        nearest = n1.nearest\n        dist_sqd = n1.dist_sqd\n        nodes_visited += n1.nodes_visited\n\n        if dist_sqd < max_dist_sqd:\n            max_dist_sqd = dist_sqd\n        d = (pivot[s] - target[s]) ** 2\n        if d > max_dist_sqd:\n            return T3(nearest, dist_sqd, nodes_visited)\n        d = sqd(pivot, target)\n        if d < dist_sqd:\n            nearest = pivot\n            dist_sqd = d\n            max_dist_sqd = dist_sqd\n\n        n2 = nn(further_kd, target, further_hr, max_dist_sqd)\n        nodes_visited += n2.nodes_visited\n        if n2.dist_sqd < dist_sqd:\n            nearest = n2.nearest\n            dist_sqd = n2.dist_sqd\n\n        return T3(nearest, dist_sqd, nodes_visited)\n\n    return nn(t.n, p, t.bounds, float(\"inf\"))\n\n\ndef show_nearest(k, heading, kd, p):\n    print(heading + \":\")\n    print(\"Point:           \", p)\n    n = find_nearest(k, kd, p)\n    print(\"Nearest neighbor:\", n.nearest)\n    print(\"Distance:        \", sqrt(n.dist_sqd))\n    print(\"Nodes visited:   \", n.nodes_visited, \"\\n\")\n\n\ndef random_point(k):\n    return [random() for _ in range(k)]\n\n\ndef random_points(k, n):\n    return [random_point(k) for _ in range(n)]\n\nif __name__ == \"__main__\":\n    seed(1)\n    P = lambda *coords: list(coords)\n    kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],\n                  Orthotope(P(0, 0), P(10, 10)))\n    show_nearest(2, \"Wikipedia example data\", kd1, P(9, 2))\n\n    N = 400000\n    t0 = time()\n    kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))\n    t1 = time()\n    text = lambda *parts: \"\".join(map(str, parts))\n    show_nearest(2, text(\"k-d tree with \", N,\n                         \" random 3D points (generation time: \",\n                         t1-t0, \"s)\"),\n                 kd2, random_point(3))\n", "Go": "\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\n\ntype point []float64\n\n\nfunc (p point) sqd(q point) float64 {\n    var sum float64\n    for dim, pCoord := range p {\n        d := pCoord - q[dim]\n        sum += d * d\n    }\n    return sum\n}\n\n\n\n\ntype kdNode struct {\n    domElt      point\n    split       int\n    left, right *kdNode\n}   \n\ntype kdTree struct {\n    n      *kdNode\n    bounds hyperRect\n}\n    \ntype hyperRect struct {\n    min, max point\n}\n\n\n\nfunc (hr hyperRect) copy() hyperRect {\n    return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}\n}   \n    \n\n\n\nfunc newKd(pts []point, bounds hyperRect) kdTree {\n    var nk2 func([]point, int) *kdNode\n    nk2 = func(exset []point, split int) *kdNode {\n        if len(exset) == 0 {\n            return nil\n        }\n        \n        \n        \n        sort.Sort(part{exset, split})\n        m := len(exset) / 2\n        d := exset[m]\n        for m+1 < len(exset) && exset[m+1][split] == d[split] {\n            m++\n        }\n        \n        s2 := split + 1\n        if s2 == len(d) {\n            s2 = 0\n        }\n        return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}\n    }\n    return kdTree{nk2(pts, 0), bounds}\n}\n\n\n\ntype part struct {\n    pts   []point\n    dPart int\n}\n\n\nfunc (p part) Len() int { return len(p.pts) }\nfunc (p part) Less(i, j int) bool {\n    return p.pts[i][p.dPart] < p.pts[j][p.dPart]\n}\nfunc (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }\n\n\n\n\n\nfunc (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {\n    return nn(t.n, p, t.bounds, math.Inf(1))\n}\n\n\n\nfunc nn(kd *kdNode, target point, hr hyperRect,\n    maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {\n    if kd == nil {\n        return nil, math.Inf(1), 0\n    }\n    nodesVisited++\n    s := kd.split\n    pivot := kd.domElt\n    leftHr := hr.copy()\n    rightHr := hr.copy()\n    leftHr.max[s] = pivot[s]\n    rightHr.min[s] = pivot[s]\n    targetInLeft := target[s] <= pivot[s]\n    var nearerKd, furtherKd *kdNode\n    var nearerHr, furtherHr hyperRect\n    if targetInLeft {\n        nearerKd, nearerHr = kd.left, leftHr\n        furtherKd, furtherHr = kd.right, rightHr\n    } else {\n        nearerKd, nearerHr = kd.right, rightHr\n        furtherKd, furtherHr = kd.left, leftHr\n    }\n    var nv int\n    nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)\n    nodesVisited += nv\n    if distSqd < maxDistSqd {\n        maxDistSqd = distSqd\n    }\n    d := pivot[s] - target[s]\n    d *= d\n    if d > maxDistSqd {\n        return\n    }\n    if d = pivot.sqd(target); d < distSqd {\n        nearest = pivot\n        distSqd = d\n        maxDistSqd = distSqd\n    }\n    tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)\n    nodesVisited += nv\n    if tempSqd < distSqd {\n        nearest = tempNearest\n        distSqd = tempSqd\n    }\n    return\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},\n        hyperRect{point{0, 0}, point{10, 10}})\n    showNearest(\"WP example data\", kd, point{9, 2})\n    kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})\n    showNearest(\"1000 random 3d points\", kd, randomPt(3))\n}   \n    \nfunc randomPt(dim int) point {\n    p := make(point, dim)\n    for d := range p {\n        p[d] = rand.Float64()\n    }\n    return p\n}   \n    \nfunc randomPts(dim, n int) []point {\n    p := make([]point, n)\n    for i := range p {\n        p[i] = randomPt(dim) \n    } \n    return p\n}\n    \nfunc showNearest(heading string, kd kdTree, p point) {\n    fmt.Println()\n    fmt.Println(heading)\n    fmt.Println(\"point:           \", p)\n    nn, ssq, nv := kd.nearest(p)\n    fmt.Println(\"nearest neighbor:\", nn)\n    fmt.Println(\"distance:        \", math.Sqrt(ssq))\n    fmt.Println(\"nodes visited:   \", nv)\n}\n"}
{"id": 44608, "name": "K-d tree", "Python": "from random import seed, random\nfrom time import time\nfrom operator import itemgetter\nfrom collections import namedtuple\nfrom math import sqrt\nfrom copy import deepcopy\n\n\ndef sqd(p1, p2):\n    return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))\n\n\nclass KdNode(object):\n    __slots__ = (\"dom_elt\", \"split\", \"left\", \"right\")\n\n    def __init__(self, dom_elt, split, left, right):\n        self.dom_elt = dom_elt\n        self.split = split\n        self.left = left\n        self.right = right\n\n\nclass Orthotope(object):\n    __slots__ = (\"min\", \"max\")\n\n    def __init__(self, mi, ma):\n        self.min, self.max = mi, ma\n\n\nclass KdTree(object):\n    __slots__ = (\"n\", \"bounds\")\n\n    def __init__(self, pts, bounds):\n        def nk2(split, exset):\n            if not exset:\n                return None\n            exset.sort(key=itemgetter(split))\n            m = len(exset) // 2\n            d = exset[m]\n            while m + 1 < len(exset) and exset[m + 1][split] == d[split]:\n                m += 1\n            d = exset[m]\n\n\n            s2 = (split + 1) % len(d)  \n            return KdNode(d, split, nk2(s2, exset[:m]),\n                                    nk2(s2, exset[m + 1:]))\n        self.n = nk2(0, pts)\n        self.bounds = bounds\n\nT3 = namedtuple(\"T3\", \"nearest dist_sqd nodes_visited\")\n\n\ndef find_nearest(k, t, p):\n    def nn(kd, target, hr, max_dist_sqd):\n        if kd is None:\n            return T3([0.0] * k, float(\"inf\"), 0)\n\n        nodes_visited = 1\n        s = kd.split\n        pivot = kd.dom_elt\n        left_hr = deepcopy(hr)\n        right_hr = deepcopy(hr)\n        left_hr.max[s] = pivot[s]\n        right_hr.min[s] = pivot[s]\n\n        if target[s] <= pivot[s]:\n            nearer_kd, nearer_hr = kd.left, left_hr\n            further_kd, further_hr = kd.right, right_hr\n        else:\n            nearer_kd, nearer_hr = kd.right, right_hr\n            further_kd, further_hr = kd.left, left_hr\n\n        n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)\n        nearest = n1.nearest\n        dist_sqd = n1.dist_sqd\n        nodes_visited += n1.nodes_visited\n\n        if dist_sqd < max_dist_sqd:\n            max_dist_sqd = dist_sqd\n        d = (pivot[s] - target[s]) ** 2\n        if d > max_dist_sqd:\n            return T3(nearest, dist_sqd, nodes_visited)\n        d = sqd(pivot, target)\n        if d < dist_sqd:\n            nearest = pivot\n            dist_sqd = d\n            max_dist_sqd = dist_sqd\n\n        n2 = nn(further_kd, target, further_hr, max_dist_sqd)\n        nodes_visited += n2.nodes_visited\n        if n2.dist_sqd < dist_sqd:\n            nearest = n2.nearest\n            dist_sqd = n2.dist_sqd\n\n        return T3(nearest, dist_sqd, nodes_visited)\n\n    return nn(t.n, p, t.bounds, float(\"inf\"))\n\n\ndef show_nearest(k, heading, kd, p):\n    print(heading + \":\")\n    print(\"Point:           \", p)\n    n = find_nearest(k, kd, p)\n    print(\"Nearest neighbor:\", n.nearest)\n    print(\"Distance:        \", sqrt(n.dist_sqd))\n    print(\"Nodes visited:   \", n.nodes_visited, \"\\n\")\n\n\ndef random_point(k):\n    return [random() for _ in range(k)]\n\n\ndef random_points(k, n):\n    return [random_point(k) for _ in range(n)]\n\nif __name__ == \"__main__\":\n    seed(1)\n    P = lambda *coords: list(coords)\n    kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],\n                  Orthotope(P(0, 0), P(10, 10)))\n    show_nearest(2, \"Wikipedia example data\", kd1, P(9, 2))\n\n    N = 400000\n    t0 = time()\n    kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))\n    t1 = time()\n    text = lambda *parts: \"\".join(map(str, parts))\n    show_nearest(2, text(\"k-d tree with \", N,\n                         \" random 3D points (generation time: \",\n                         t1-t0, \"s)\"),\n                 kd2, random_point(3))\n", "Go": "\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\n\ntype point []float64\n\n\nfunc (p point) sqd(q point) float64 {\n    var sum float64\n    for dim, pCoord := range p {\n        d := pCoord - q[dim]\n        sum += d * d\n    }\n    return sum\n}\n\n\n\n\ntype kdNode struct {\n    domElt      point\n    split       int\n    left, right *kdNode\n}   \n\ntype kdTree struct {\n    n      *kdNode\n    bounds hyperRect\n}\n    \ntype hyperRect struct {\n    min, max point\n}\n\n\n\nfunc (hr hyperRect) copy() hyperRect {\n    return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}\n}   \n    \n\n\n\nfunc newKd(pts []point, bounds hyperRect) kdTree {\n    var nk2 func([]point, int) *kdNode\n    nk2 = func(exset []point, split int) *kdNode {\n        if len(exset) == 0 {\n            return nil\n        }\n        \n        \n        \n        sort.Sort(part{exset, split})\n        m := len(exset) / 2\n        d := exset[m]\n        for m+1 < len(exset) && exset[m+1][split] == d[split] {\n            m++\n        }\n        \n        s2 := split + 1\n        if s2 == len(d) {\n            s2 = 0\n        }\n        return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}\n    }\n    return kdTree{nk2(pts, 0), bounds}\n}\n\n\n\ntype part struct {\n    pts   []point\n    dPart int\n}\n\n\nfunc (p part) Len() int { return len(p.pts) }\nfunc (p part) Less(i, j int) bool {\n    return p.pts[i][p.dPart] < p.pts[j][p.dPart]\n}\nfunc (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }\n\n\n\n\n\nfunc (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {\n    return nn(t.n, p, t.bounds, math.Inf(1))\n}\n\n\n\nfunc nn(kd *kdNode, target point, hr hyperRect,\n    maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {\n    if kd == nil {\n        return nil, math.Inf(1), 0\n    }\n    nodesVisited++\n    s := kd.split\n    pivot := kd.domElt\n    leftHr := hr.copy()\n    rightHr := hr.copy()\n    leftHr.max[s] = pivot[s]\n    rightHr.min[s] = pivot[s]\n    targetInLeft := target[s] <= pivot[s]\n    var nearerKd, furtherKd *kdNode\n    var nearerHr, furtherHr hyperRect\n    if targetInLeft {\n        nearerKd, nearerHr = kd.left, leftHr\n        furtherKd, furtherHr = kd.right, rightHr\n    } else {\n        nearerKd, nearerHr = kd.right, rightHr\n        furtherKd, furtherHr = kd.left, leftHr\n    }\n    var nv int\n    nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)\n    nodesVisited += nv\n    if distSqd < maxDistSqd {\n        maxDistSqd = distSqd\n    }\n    d := pivot[s] - target[s]\n    d *= d\n    if d > maxDistSqd {\n        return\n    }\n    if d = pivot.sqd(target); d < distSqd {\n        nearest = pivot\n        distSqd = d\n        maxDistSqd = distSqd\n    }\n    tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)\n    nodesVisited += nv\n    if tempSqd < distSqd {\n        nearest = tempNearest\n        distSqd = tempSqd\n    }\n    return\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},\n        hyperRect{point{0, 0}, point{10, 10}})\n    showNearest(\"WP example data\", kd, point{9, 2})\n    kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})\n    showNearest(\"1000 random 3d points\", kd, randomPt(3))\n}   \n    \nfunc randomPt(dim int) point {\n    p := make(point, dim)\n    for d := range p {\n        p[d] = rand.Float64()\n    }\n    return p\n}   \n    \nfunc randomPts(dim, n int) []point {\n    p := make([]point, n)\n    for i := range p {\n        p[i] = randomPt(dim) \n    } \n    return p\n}\n    \nfunc showNearest(heading string, kd kdTree, p point) {\n    fmt.Println()\n    fmt.Println(heading)\n    fmt.Println(\"point:           \", p)\n    nn, ssq, nv := kd.nearest(p)\n    fmt.Println(\"nearest neighbor:\", nn)\n    fmt.Println(\"distance:        \", math.Sqrt(ssq))\n    fmt.Println(\"nodes visited:   \", nv)\n}\n"}
{"id": 44609, "name": "Apply a callback to an array", "Python": "def square(n):\n    return n * n\n  \nnumbers = [1, 3, 5, 7]\n\nsquares1 = [square(n) for n in numbers]     \n\nsquares2a = map(square, numbers)            \n\nsquares2b = map(lambda x: x*x, numbers)     \n\nsquares3 = [n * n for n in numbers]         \n                                            \n\nisquares1 = (n * n for n in numbers)        \n\nimport itertools\nisquares2 = itertools.imap(square, numbers) \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, i := range []int{1, 2, 3, 4, 5} {\n        fmt.Println(i * i)\n    }\n}\n"}
{"id": 44610, "name": "Apply a callback to an array", "Python": "def square(n):\n    return n * n\n  \nnumbers = [1, 3, 5, 7]\n\nsquares1 = [square(n) for n in numbers]     \n\nsquares2a = map(square, numbers)            \n\nsquares2b = map(lambda x: x*x, numbers)     \n\nsquares3 = [n * n for n in numbers]         \n                                            \n\nisquares1 = (n * n for n in numbers)        \n\nimport itertools\nisquares2 = itertools.imap(square, numbers) \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, i := range []int{1, 2, 3, 4, 5} {\n        fmt.Println(i * i)\n    }\n}\n"}
{"id": 44611, "name": "Singleton", "Python": ">>> class Borg(object):\n\t__state = {}\n\tdef __init__(self):\n\t\tself.__dict__ = self.__state\n\t\n\n\t\n>>> b1 = Borg()\n>>> b2 = Borg()\n>>> b1 is b2\nFalse\n>>> b1.datum = range(5)\n>>> b1.datum\n[0, 1, 2, 3, 4]\n>>> b2.datum\n[0, 1, 2, 3, 4]\n>>> b1.datum is b2.datum\nTrue\n>>> \n", "Go": "package main\n\nimport (\n    \"log\"\n    \"math/rand\"\n    \"sync\"\n    \"time\"\n)\n\nvar (\n    instance string\n    once     sync.Once \n)\n\nfunc claim(color string, w *sync.WaitGroup) {\n    time.Sleep(time.Duration(rand.Intn(1e8))) \n    log.Println(\"trying to claim\", color)\n    once.Do(func() { instance = color })\n    log.Printf(\"tried %s. instance: %s\", color, instance)\n    w.Done()\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    var w sync.WaitGroup\n    w.Add(2)\n    go claim(\"red\", &w) \n    go claim(\"blue\", &w)\n    w.Wait()\n    log.Println(\"after trying both, instance =\", instance)\n}\n"}
{"id": 44612, "name": "Safe addition", "Python": ">>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])\n0.9999999999999999\n>>> from math import fsum\n>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])\n1.0\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype interval struct {\n    lower, upper float64\n}\n\n\nfunc stepAway(x float64) interval {\n    return interval {\n        math.Nextafter(x, math.Inf(-1)),\n        math.Nextafter(x, math.Inf(1))}\n}\n\n\nfunc safeAdd(a, b float64) interval {\n    return stepAway(a + b)\n    \n}\n\n\nfunc main() {\n    a, b := 1.2, .03\n    fmt.Println(a, b, safeAdd(a, b))\n}\n"}
{"id": 44613, "name": "Case-sensitivity of identifiers", "Python": ">>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'\n>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)\nThe three dogs are named  Benjamin ,  Samba , and  Bernie\n>>>\n", "Go": "package dogs\n\nimport \"fmt\"\n\n\n\nvar dog = \"Salt\"\nvar Dog = \"Pepper\"\nvar DOG = \"Mustard\"\n\nfunc PackageSees() map[*string]int {\n    \n    fmt.Println(\"Package sees:\", dog, Dog, DOG)\n    \n    \n    \n    \n    return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}\n}\n"}
{"id": 44614, "name": "Case-sensitivity of identifiers", "Python": ">>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'\n>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)\nThe three dogs are named  Benjamin ,  Samba , and  Bernie\n>>>\n", "Go": "package dogs\n\nimport \"fmt\"\n\n\n\nvar dog = \"Salt\"\nvar Dog = \"Pepper\"\nvar DOG = \"Mustard\"\n\nfunc PackageSees() map[*string]int {\n    \n    fmt.Println(\"Package sees:\", dog, Dog, DOG)\n    \n    \n    \n    \n    return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}\n}\n"}
{"id": 44615, "name": "Loops_Downward for", "Python": "for i in xrange(10, -1, -1):\n    print i\n", "Go": "for i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n"}
{"id": 44616, "name": "Write entire file", "Python": "with open(filename, 'w') as f:\n    f.write(data)\n", "Go": "import \"io/ioutil\"\n\nfunc main() {\n    ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n"}
{"id": 44617, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 5; i++ {\n        for j := 1; j <= i; j++ {\n            fmt.Printf(\"*\")\n        }\n        fmt.Printf(\"\\n\")\n    }\n}\n"}
{"id": 44618, "name": "Loops_For", "Python": "for i in 1..5:\n  for j in 1..i:\n    stdout.write(\"*\")\n  echo(\"\")\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 5; i++ {\n        for j := 1; j <= i; j++ {\n            fmt.Printf(\"*\")\n        }\n        fmt.Printf(\"\\n\")\n    }\n}\n"}
{"id": 44619, "name": "Palindromic gapful numbers", "Python": "from itertools import count\nfrom pprint import pformat\nimport re\nimport heapq\n\n\ndef pal_part_gen(odd=True):\n    for i in count(1):\n        fwd = str(i)\n        rev = fwd[::-1][1:] if odd else fwd[::-1]\n        yield int(fwd + rev)\n\ndef pal_ordered_gen():\n    yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))\n\ndef is_gapful(x):\n    return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)\n\nif __name__ == '__main__':\n    start = 100\n    for mx, last in [(20, 20), (100, 15), (1_000, 10)]:\n        print(f\"\\nLast {last} of the first {mx} binned-by-last digit \" \n              f\"gapful numbers >= {start}\")\n        bin = {i: [] for i in range(1, 10)}\n        gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))\n        while any(len(val) < mx for val in bin.values()):\n            g = next(gen)\n            val = bin[g % 10]\n            if len(val) < mx:\n                val.append(g)\n        b = {k:v[-last:] for k, v in bin.items()}\n        txt = pformat(b, width=220)\n        print('', re.sub(r\"[{},\\[\\]]\", '', txt))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(s uint64) uint64 {\n    e := uint64(0)\n    for s > 0 {\n        e = e*10 + (s % 10)\n        s /= 10\n    }\n    return e\n}\n\nfunc commatize(n uint) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc ord(n uint) string {\n    var suffix string\n    if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {\n        suffix = \"th\"\n    } else {\n        switch n % 10 {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        default:\n            suffix = \"th\"\n        }\n    }\n    return fmt.Sprintf(\"%s%s\", commatize(n), suffix)\n}\n\nfunc main() {\n    const max = 10_000_000\n    data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},\n        {1e6, 1e6, 16}, {1e7, 1e7, 18}}\n    results := make(map[uint][]uint64)\n    for _, d := range data {\n        for i := d[0]; i <= d[1]; i++ {\n            results[i] = make([]uint64, 9)\n        }\n    }\n    var p uint64\nouter:\n    for d := uint64(1); d < 10; d++ {\n        count := uint(0)\n        pow := uint64(1)\n        fl := d * 11\n        for nd := 3; nd < 20; nd++ {\n            slim := (d + 1) * pow\n            for s := d * pow; s < slim; s++ {\n                e := reverse(s)\n                mlim := uint64(1)\n                if nd%2 == 1 {\n                    mlim = 10\n                }\n                for m := uint64(0); m < mlim; m++ {\n                    if nd%2 == 0 {\n                        p = s*pow*10 + e\n                    } else {\n                        p = s*pow*100 + m*pow*10 + e\n                    }\n                    if p%fl == 0 {\n                        count++\n                        if _, ok := results[count]; ok {\n                            results[count][d-1] = p\n                        }\n                        if count == max {\n                            continue outer\n                        }\n                    }\n                }\n            }\n            if nd%2 == 1 {\n                pow *= 10\n            }\n        }\n    }\n\n    for _, d := range data {\n        if d[0] != d[1] {\n            fmt.Printf(\"%s to %s palindromic gapful numbers (> 100) ending with:\\n\", ord(d[0]), ord(d[1]))\n        } else {\n            fmt.Printf(\"%s palindromic gapful number (> 100) ending with:\\n\", ord(d[0]))\n        }\n        for i := 1; i <= 9; i++ {\n            fmt.Printf(\"%d: \", i)\n            for j := d[0]; j <= d[1]; j++ {\n                fmt.Printf(\"%*d \", d[2], results[j][i-1])\n            }\n            fmt.Println()\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 44620, "name": "Palindromic gapful numbers", "Python": "from itertools import count\nfrom pprint import pformat\nimport re\nimport heapq\n\n\ndef pal_part_gen(odd=True):\n    for i in count(1):\n        fwd = str(i)\n        rev = fwd[::-1][1:] if odd else fwd[::-1]\n        yield int(fwd + rev)\n\ndef pal_ordered_gen():\n    yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))\n\ndef is_gapful(x):\n    return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)\n\nif __name__ == '__main__':\n    start = 100\n    for mx, last in [(20, 20), (100, 15), (1_000, 10)]:\n        print(f\"\\nLast {last} of the first {mx} binned-by-last digit \" \n              f\"gapful numbers >= {start}\")\n        bin = {i: [] for i in range(1, 10)}\n        gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))\n        while any(len(val) < mx for val in bin.values()):\n            g = next(gen)\n            val = bin[g % 10]\n            if len(val) < mx:\n                val.append(g)\n        b = {k:v[-last:] for k, v in bin.items()}\n        txt = pformat(b, width=220)\n        print('', re.sub(r\"[{},\\[\\]]\", '', txt))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc reverse(s uint64) uint64 {\n    e := uint64(0)\n    for s > 0 {\n        e = e*10 + (s % 10)\n        s /= 10\n    }\n    return e\n}\n\nfunc commatize(n uint) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc ord(n uint) string {\n    var suffix string\n    if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {\n        suffix = \"th\"\n    } else {\n        switch n % 10 {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        default:\n            suffix = \"th\"\n        }\n    }\n    return fmt.Sprintf(\"%s%s\", commatize(n), suffix)\n}\n\nfunc main() {\n    const max = 10_000_000\n    data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},\n        {1e6, 1e6, 16}, {1e7, 1e7, 18}}\n    results := make(map[uint][]uint64)\n    for _, d := range data {\n        for i := d[0]; i <= d[1]; i++ {\n            results[i] = make([]uint64, 9)\n        }\n    }\n    var p uint64\nouter:\n    for d := uint64(1); d < 10; d++ {\n        count := uint(0)\n        pow := uint64(1)\n        fl := d * 11\n        for nd := 3; nd < 20; nd++ {\n            slim := (d + 1) * pow\n            for s := d * pow; s < slim; s++ {\n                e := reverse(s)\n                mlim := uint64(1)\n                if nd%2 == 1 {\n                    mlim = 10\n                }\n                for m := uint64(0); m < mlim; m++ {\n                    if nd%2 == 0 {\n                        p = s*pow*10 + e\n                    } else {\n                        p = s*pow*100 + m*pow*10 + e\n                    }\n                    if p%fl == 0 {\n                        count++\n                        if _, ok := results[count]; ok {\n                            results[count][d-1] = p\n                        }\n                        if count == max {\n                            continue outer\n                        }\n                    }\n                }\n            }\n            if nd%2 == 1 {\n                pow *= 10\n            }\n        }\n    }\n\n    for _, d := range data {\n        if d[0] != d[1] {\n            fmt.Printf(\"%s to %s palindromic gapful numbers (> 100) ending with:\\n\", ord(d[0]), ord(d[1]))\n        } else {\n            fmt.Printf(\"%s palindromic gapful number (> 100) ending with:\\n\", ord(d[0]))\n        }\n        for i := 1; i <= 9; i++ {\n            fmt.Printf(\"%d: \", i)\n            for j := d[0]; j <= d[1]; j++ {\n                fmt.Printf(\"%*d \", d[2], results[j][i-1])\n            }\n            fmt.Println()\n        }\n        fmt.Println()\n    }\n}\n"}
{"id": 44621, "name": "Sierpinski triangle_Graphical", "Python": "\nimport turtle as t\ndef sier(n,length):\n    if n == 0:\n        return\n    for i in range(3):\n        sier(n - 1, length / 2)\n        t.fd(length)\n        t.rt(120)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"os\"\n)\n\nfunc main() {\n    const order = 8\n    const width = 1 << order\n    const margin = 10\n    bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)\n    im := image.NewGray(bounds)\n    gBlack := color.Gray{0}\n    gWhite := color.Gray{255}\n    draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)\n\n    for y := 0; y < width; y++ {\n        for x := 0; x < width; x++ {\n            if x&y == 0 {\n                im.SetGray(x, y, gBlack)\n            }\n        }\n    }\n    f, err := os.Create(\"sierpinski.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, im); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 44622, "name": "Sierpinski triangle_Graphical", "Python": "\nimport turtle as t\ndef sier(n,length):\n    if n == 0:\n        return\n    for i in range(3):\n        sier(n - 1, length / 2)\n        t.fd(length)\n        t.rt(120)\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"os\"\n)\n\nfunc main() {\n    const order = 8\n    const width = 1 << order\n    const margin = 10\n    bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)\n    im := image.NewGray(bounds)\n    gBlack := color.Gray{0}\n    gWhite := color.Gray{255}\n    draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)\n\n    for y := 0; y < width; y++ {\n        for x := 0; x < width; x++ {\n            if x&y == 0 {\n                im.SetGray(x, y, gBlack)\n            }\n        }\n    }\n    f, err := os.Create(\"sierpinski.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, im); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 44623, "name": "Summarize primes", "Python": "\n\n\nfrom itertools import accumulate, chain, takewhile\n\n\n\ndef primeSums():\n    \n    return (\n        x for x in enumerate(\n            accumulate(\n                chain([(0, 0)], primes()),\n                lambda a, p: (p, p + a[1])\n            )\n        ) if isPrime(x[1][1])\n    )\n\n\n\n\ndef main():\n    \n    for x in takewhile(\n            lambda t: 1000 > t[1][0],\n            primeSums()\n    ):\n        print(f'{x[0]} -> {x[1][1]}')\n\n\n\n\n\ndef isPrime(n):\n    \n    if n in (2, 3):\n        return True\n    if 2 > n or 0 == n % 2:\n        return False\n    if 9 > n:\n        return True\n    if 0 == n % 3:\n        return False\n\n    def p(x):\n        return 0 == n % x or 0 == n % (2 + x)\n\n    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))\n\n\n\ndef primes():\n    \n    n = 2\n    dct = {}\n    while True:\n        if n in dct:\n            for p in dct[n]:\n                dct.setdefault(n + p, []).append(p)\n            del dct[n]\n        else:\n            yield n\n            dct[n * n] = [n]\n        n = 1 + n\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum, n, c := 0, 0, 0\n    fmt.Println(\"Summing the first n primes (<1,000) where the sum is itself prime:\")\n    fmt.Println(\"  n  cumulative sum\")\n    for _, p := range primes {\n        n++\n        sum += p\n        if rcu.IsPrime(sum) {\n            c++\n            fmt.Printf(\"%3d   %6s\\n\", n, rcu.Commatize(sum))\n        }\n    }\n    fmt.Println()\n    fmt.Println(c, \"such prime sums found\")\n}\n"}
{"id": 44624, "name": "Summarize primes", "Python": "\n\n\nfrom itertools import accumulate, chain, takewhile\n\n\n\ndef primeSums():\n    \n    return (\n        x for x in enumerate(\n            accumulate(\n                chain([(0, 0)], primes()),\n                lambda a, p: (p, p + a[1])\n            )\n        ) if isPrime(x[1][1])\n    )\n\n\n\n\ndef main():\n    \n    for x in takewhile(\n            lambda t: 1000 > t[1][0],\n            primeSums()\n    ):\n        print(f'{x[0]} -> {x[1][1]}')\n\n\n\n\n\ndef isPrime(n):\n    \n    if n in (2, 3):\n        return True\n    if 2 > n or 0 == n % 2:\n        return False\n    if 9 > n:\n        return True\n    if 0 == n % 3:\n        return False\n\n    def p(x):\n        return 0 == n % x or 0 == n % (2 + x)\n\n    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))\n\n\n\ndef primes():\n    \n    n = 2\n    dct = {}\n    while True:\n        if n in dct:\n            for p in dct[n]:\n                dct.setdefault(n + p, []).append(p)\n            del dct[n]\n        else:\n            yield n\n            dct[n * n] = [n]\n        n = 1 + n\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"rcu\"\n)\n\nfunc main() {\n    primes := rcu.Primes(999)\n    sum, n, c := 0, 0, 0\n    fmt.Println(\"Summing the first n primes (<1,000) where the sum is itself prime:\")\n    fmt.Println(\"  n  cumulative sum\")\n    for _, p := range primes {\n        n++\n        sum += p\n        if rcu.IsPrime(sum) {\n            c++\n            fmt.Printf(\"%3d   %6s\\n\", n, rcu.Commatize(sum))\n        }\n    }\n    fmt.Println()\n    fmt.Println(c, \"such prime sums found\")\n}\n"}
{"id": 44625, "name": "Common sorted list", "Python": "\n\nfrom itertools import chain\n\n\n\n\ndef main():\n    \n\n    print(\n        sorted(nub(concat([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ])))\n    )\n\n\n\n\n\n\ndef concat(xs):\n    \n    return list(chain(*xs))\n\n\n\ndef nub(xs):\n    \n    return list(dict.fromkeys(xs))\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc distinctSortedUnion(ll [][]int) []int {\n    var res []int\n    for _, l := range ll {\n        res = append(res, l...)\n    }\n    set := make(map[int]bool)\n    for _, e := range res {\n        set[e] = true\n    }\n    res = res[:0]\n    for key := range set {\n        res = append(res, key)\n    }\n    sort.Ints(res)\n    return res\n}\n\nfunc main() {\n    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}\n    fmt.Println(\"Distinct sorted union of\", ll, \"is:\")\n    fmt.Println(distinctSortedUnion(ll))\n}\n"}
{"id": 44626, "name": "Common sorted list", "Python": "\n\nfrom itertools import chain\n\n\n\n\ndef main():\n    \n\n    print(\n        sorted(nub(concat([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ])))\n    )\n\n\n\n\n\n\ndef concat(xs):\n    \n    return list(chain(*xs))\n\n\n\ndef nub(xs):\n    \n    return list(dict.fromkeys(xs))\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc distinctSortedUnion(ll [][]int) []int {\n    var res []int\n    for _, l := range ll {\n        res = append(res, l...)\n    }\n    set := make(map[int]bool)\n    for _, e := range res {\n        set[e] = true\n    }\n    res = res[:0]\n    for key := range set {\n        res = append(res, key)\n    }\n    sort.Ints(res)\n    return res\n}\n\nfunc main() {\n    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}\n    fmt.Println(\"Distinct sorted union of\", ll, \"is:\")\n    fmt.Println(distinctSortedUnion(ll))\n}\n"}
{"id": 44627, "name": "Common sorted list", "Python": "\n\nfrom itertools import chain\n\n\n\n\ndef main():\n    \n\n    print(\n        sorted(nub(concat([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ])))\n    )\n\n\n\n\n\n\ndef concat(xs):\n    \n    return list(chain(*xs))\n\n\n\ndef nub(xs):\n    \n    return list(dict.fromkeys(xs))\n\n\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc distinctSortedUnion(ll [][]int) []int {\n    var res []int\n    for _, l := range ll {\n        res = append(res, l...)\n    }\n    set := make(map[int]bool)\n    for _, e := range res {\n        set[e] = true\n    }\n    res = res[:0]\n    for key := range set {\n        res = append(res, key)\n    }\n    sort.Ints(res)\n    return res\n}\n\nfunc main() {\n    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}\n    fmt.Println(\"Distinct sorted union of\", ll, \"is:\")\n    fmt.Println(distinctSortedUnion(ll))\n}\n"}
{"id": 44628, "name": "Non-continuous subsequences", "Python": "def ncsub(seq, s=0):\n    if seq:\n        x = seq[:1]\n        xs = seq[1:]\n        p2 = s % 2\n        p1 = not p2\n        return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)\n    else:\n        return [[]] if s >= 3 else []\n", "Go": "package main\n\nimport \"fmt\"\n\nconst ( \n    m   = iota \n    c          \n    cm         \n    cmc        \n)\n\nfunc ncs(s []int) [][]int {\n    if len(s) < 3 {\n        return nil\n    }\n    return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)\n}\n\nvar skip = []int{m, cm, cm, cmc}\nvar incl = []int{c, c, cmc, cmc}\n\nfunc n2(ss, tail []int, seq int) [][]int {\n    if len(tail) == 0 {\n        if seq != cmc {\n            return nil\n        }\n        return [][]int{ss}\n    }\n    return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),\n        n2(append(ss, tail[0]), tail[1:], incl[seq])...)\n}\n\nfunc main() {\n    ss := ncs([]int{1, 2, 3, 4})\n    fmt.Println(len(ss), \"non-continuous subsequences:\")\n    for _, s := range ss {\n        fmt.Println(\"  \", s)\n    }\n}\n"}
{"id": 44629, "name": "Non-continuous subsequences", "Python": "def ncsub(seq, s=0):\n    if seq:\n        x = seq[:1]\n        xs = seq[1:]\n        p2 = s % 2\n        p1 = not p2\n        return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)\n    else:\n        return [[]] if s >= 3 else []\n", "Go": "package main\n\nimport \"fmt\"\n\nconst ( \n    m   = iota \n    c          \n    cm         \n    cmc        \n)\n\nfunc ncs(s []int) [][]int {\n    if len(s) < 3 {\n        return nil\n    }\n    return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)\n}\n\nvar skip = []int{m, cm, cm, cmc}\nvar incl = []int{c, c, cmc, cmc}\n\nfunc n2(ss, tail []int, seq int) [][]int {\n    if len(tail) == 0 {\n        if seq != cmc {\n            return nil\n        }\n        return [][]int{ss}\n    }\n    return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),\n        n2(append(ss, tail[0]), tail[1:], incl[seq])...)\n}\n\nfunc main() {\n    ss := ncs([]int{1, 2, 3, 4})\n    fmt.Println(len(ss), \"non-continuous subsequences:\")\n    for _, s := range ss {\n        fmt.Println(\"  \", s)\n    }\n}\n"}
{"id": 44630, "name": "Fibonacci word_fractal", "Python": "from functools import wraps\nfrom turtle import *\n\ndef memoize(obj):\n    cache = obj.cache = {}\n    @wraps(obj)\n    def memoizer(*args, **kwargs):\n        key = str(args) + str(kwargs)\n        if key not in cache:\n            cache[key] = obj(*args, **kwargs)\n        return cache[key]\n    return memoizer\n\n@memoize\ndef fibonacci_word(n):\n    assert n > 0\n    if n == 1:\n        return \"1\"\n    if n == 2:\n        return \"0\"\n    return fibonacci_word(n - 1) + fibonacci_word(n - 2)\n\ndef draw_fractal(word, step):\n    for i, c in enumerate(word, 1):\n        forward(step)\n        if c == \"0\":\n            if i % 2 == 0:\n                left(90)\n            else:\n                right(90)\n\ndef main():\n    n = 25 \n    step = 1 \n    width = 1050 \n    height = 1050 \n    w = fibonacci_word(n)\n\n    setup(width=width, height=height)\n    speed(0)\n    setheading(90)\n    left(90)\n    penup()\n    forward(500)\n    right(90)\n    backward(500)\n    pendown()\n    tracer(10000)\n    hideturtle()\n\n    draw_fractal(w, step)\n\n    \n    getscreen().getcanvas().postscript(file=\"fibonacci_word_fractal.eps\")\n    exitonclick()\n\nif __name__ == '__main__':\n    main()\n", "Go": "package main\n\nimport (\n    \"github.com/fogleman/gg\"\n    \"strings\"\n)\n\nfunc wordFractal(i int) string {\n    if i < 2 {\n        if i == 1 {\n            return \"1\"\n        }\n        return \"\"\n    }\n    var f1 strings.Builder\n    f1.WriteString(\"1\")\n    var f2 strings.Builder\n    f2.WriteString(\"0\")\n    for j := i - 2; j >= 1; j-- {\n        tmp := f2.String()\n        f2.WriteString(f1.String())\n        f1.Reset()\n        f1.WriteString(tmp)\n    }\n    return f2.String()\n}\n\nfunc draw(dc *gg.Context, x, y, dx, dy float64, wf string) {\n    for i, c := range wf {\n        dc.DrawLine(x, y, x+dx, y+dy)\n        x += dx\n        y += dy\n        if c == '0' {\n            tx := dx\n            dx = dy\n            if i%2 == 0 {\n                dx = -dy\n            }\n            dy = -tx\n            if i%2 == 0 {\n                dy = tx\n            }\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(450, 620)\n    dc.SetRGB(0, 0, 0)\n    dc.Clear()\n    wf := wordFractal(23)\n    draw(dc, 20, 20, 1, 0, wf)\n    dc.SetRGB(0, 1, 0)\n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"fib_wordfractal.png\")\n}\n"}
{"id": 44631, "name": "Twin primes", "Python": "primes = [2, 3, 5, 7, 11, 13, 17, 19]\n\n\ndef count_twin_primes(limit: int) -> int:\n    global primes\n    if limit > primes[-1]:\n        ram_limit = primes[-1] + 90000000 - len(primes)\n        reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1\n\n        while reasonable_limit < limit:\n            ram_limit = primes[-1] + 90000000 - len(primes)\n            if ram_limit > primes[-1]:\n                reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)\n            else:\n                reasonable_limit = min(limit, primes[-1] ** 2)\n\n            sieve = list({x for prime in primes for x in\n                          range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})\n            primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]\n\n    count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])\n\n    return count\n\n\ndef test(limit: int):\n    count = count_twin_primes(limit)\n    print(f\"Number of twin prime pairs less than {limit} is {count}\\n\")\n\n\ntest(10)\ntest(100)\ntest(1000)\ntest(10000)\ntest(100000)\ntest(1000000)\ntest(10000000)\ntest(100000000)\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit uint64) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := uint64(3) \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc main() {\n    c := sieve(1e10 - 1)\n    limit := 10\n    start := 3\n    twins := 0\n    for i := 1; i < 11; i++ {\n        for i := start; i < limit; i += 2 {\n            if !c[i] && !c[i-2] {\n                twins++\n            }\n        }\n        fmt.Printf(\"Under %14s there are %10s pairs of twin primes.\\n\", commatize(limit), commatize(twins))\n        start = limit + 1\n        limit *= 10\n    }\n}\n"}
{"id": 44632, "name": "15 puzzle solver", "Python": "import random\n\n\nclass IDAStar:\n    def __init__(self, h, neighbours):\n        \n\n        self.h = h\n        self.neighbours = neighbours\n        self.FOUND = object()\n\n\n    def solve(self, root, is_goal, max_cost=None):\n        \n\n        self.is_goal = is_goal\n        self.path = [root]\n        self.is_in_path = {root}\n        self.path_descrs = []\n        self.nodes_evaluated = 0\n\n        bound = self.h(root)\n\n        while True:\n            t = self._search(0, bound)\n            if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated\n            if t is None: return None\n            bound = t\n\n    def _search(self, g, bound):\n        self.nodes_evaluated += 1\n\n        node = self.path[-1]\n        f = g + self.h(node)\n        if f > bound: return f\n        if self.is_goal(node): return self.FOUND\n\n        m = None \n        for cost, n, descr in self.neighbours(node):\n            if n in self.is_in_path: continue\n\n            self.path.append(n)\n            self.is_in_path.add(n)\n            self.path_descrs.append(descr)\n            t = self._search(g + cost, bound)\n\n            if t == self.FOUND: return self.FOUND\n            if m is None or (t is not None and t < m): m = t\n\n            self.path.pop()\n            self.path_descrs.pop()\n            self.is_in_path.remove(n)\n\n        return m\n\n\ndef slide_solved_state(n):\n    return tuple(i % (n*n) for i in range(1, n*n+1))\n\ndef slide_randomize(p, neighbours):\n    for _ in range(len(p) ** 2):\n        _, p, _ = random.choice(list(neighbours(p)))\n    return p\n\ndef slide_neighbours(n):\n    movelist = []\n    for gap in range(n*n):\n        x, y = gap % n, gap // n\n        moves = []\n        if x > 0: moves.append(-1)    \n        if x < n-1: moves.append(+1)  \n        if y > 0: moves.append(-n)    \n        if y < n-1: moves.append(+n)  \n        movelist.append(moves)\n\n    def neighbours(p):\n        gap = p.index(0)\n        l = list(p)\n\n        for m in movelist[gap]:\n            l[gap] = l[gap + m]\n            l[gap + m] = 0\n            yield (1, tuple(l), (l[gap], m))\n            l[gap + m] = l[gap]\n            l[gap] = 0\n\n    return neighbours\n\ndef slide_print(p):\n    n = int(round(len(p) ** 0.5))\n    l = len(str(n*n))\n    for i in range(0, len(p), n):\n        print(\" \".join(\"{:>{}}\".format(x, l) for x in p[i:i+n]))\n\ndef encode_cfg(cfg, n):\n    r = 0\n    b = n.bit_length()\n    for i in range(len(cfg)):\n        r |= cfg[i] << (b*i)\n    return r\n\n\ndef gen_wd_table(n):\n    goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)]\n    goal[-1][-1] = n - 1\n    goal = tuple(sum(goal, []))\n\n    table = {}\n    to_visit = [(goal, 0, n-1)]\n    while to_visit:\n        cfg, cost, e = to_visit.pop(0)\n        enccfg = encode_cfg(cfg, n)\n        if enccfg in table: continue\n        table[enccfg] = cost\n\n        for d in [-1, 1]:\n            if 0 <= e + d < n:\n                for c in range(n):\n                    if cfg[n*(e+d) + c] > 0:\n                        ncfg = list(cfg)\n                        ncfg[n*(e+d) + c] -= 1\n                        ncfg[n*e + c] += 1\n                        to_visit.append((tuple(ncfg), cost + 1, e+d))\n\n    return table\n\ndef slide_wd(n, goal):\n    wd = gen_wd_table(n)\n    goals = {i : goal.index(i) for i in goal}\n    b = n.bit_length()\n\n    def h(p):\n        ht = 0 \n        vt = 0 \n        d = 0\n        for i, c in enumerate(p):\n            if c == 0: continue\n            g = goals[c]\n            xi, yi = i % n, i // n\n            xg, yg = g % n, g // n\n            ht += 1 << (b*(n*yi+yg))\n            vt += 1 << (b*(n*xi+xg))\n\n            if yg == yi:\n                for k in range(i + 1, i - i%n + n): \n                    if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g:\n                        d += 2\n\n            if xg == xi:\n                for k in range(i + n, n * n, n): \n                    if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g:\n                        d += 2\n\n        d += wd[ht] + wd[vt]\n\n        return d\n    return h\n\n\n\n\nif __name__ == \"__main__\":\n    solved_state = slide_solved_state(4)\n    neighbours = slide_neighbours(4)\n    is_goal = lambda p: p == solved_state\n\n    tests = [\n        (15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2),\n    ]\n\n    slide_solver = IDAStar(slide_wd(4, solved_state), neighbours)\n\n    for p in tests:\n        path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80)\n        slide_print(p)\n        print(\", \".join({-1: \"Left\", 1: \"Right\", -4: \"Up\", 4: \"Down\"}[move[1]] for move in moves))\n        print(cost, num_eval)\n", "Go": "package main\n\nimport \"fmt\"\n\nvar (\n    Nr = [16]int{3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3}\n    Nc = [16]int{3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2}\n)\n\nvar (\n    n, _n      int\n    N0, N3, N4 [85]int\n    N2         [85]uint64\n)\n\nconst (\n    i = 1\n    g = 8\n    e = 2\n    l = 4\n)\n\nfunc fY() bool {\n    if N2[n] == 0x123456789abcdef0 {\n        return true\n    }\n    if N4[n] <= _n {\n        return fN()\n    }\n    return false\n}\n\nfunc fZ(w int) bool {\n    if w&i > 0 {\n        fI()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    if w&g > 0 {\n        fG()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    if w&e > 0 {\n        fE()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    if w&l > 0 {\n        fL()\n        if fY() {\n            return true\n        }\n        n--\n    }\n    return false\n}\n\nfunc fN() bool {\n    switch N0[n] {\n    case 0:\n        switch N3[n] {\n        case 'l':\n            return fZ(i)\n        case 'u':\n            return fZ(e)\n        default:\n            return fZ(i + e)\n        }\n    case 3:\n        switch N3[n] {\n        case 'r':\n            return fZ(i)\n        case 'u':\n            return fZ(l)\n        default:\n            return fZ(i + l)\n        }\n    case 1, 2:\n        switch N3[n] {\n        case 'l':\n            return fZ(i + l)\n        case 'r':\n            return fZ(i + e)\n        case 'u':\n            return fZ(e + l)\n        default:\n            return fZ(l + e + i)\n        }\n    case 12:\n        switch N3[n] {\n        case 'l':\n            return fZ(g)\n        case 'd':\n            return fZ(e)\n        default:\n            return fZ(e + g)\n        }\n    case 15:\n        switch N3[n] {\n        case 'r':\n            return fZ(g)\n        case 'd':\n            return fZ(l)\n        default:\n            return fZ(g + l)\n        }\n    case 13, 14:\n        switch N3[n] {\n        case 'l':\n            return fZ(g + l)\n        case 'r':\n            return fZ(e + g)\n        case 'd':\n            return fZ(e + l)\n        default:\n            return fZ(g + e + l)\n        }\n    case 4, 8:\n        switch N3[n] {\n        case 'l':\n            return fZ(i + g)\n        case 'u':\n            return fZ(g + e)\n        case 'd':\n            return fZ(i + e)\n        default:\n            return fZ(i + g + e)\n        }\n    case 7, 11:\n        switch N3[n] {\n        case 'd':\n            return fZ(i + l)\n        case 'u':\n            return fZ(g + l)\n        case 'r':\n            return fZ(i + g)\n        default:\n            return fZ(i + g + l)\n        }\n    default:\n        switch N3[n] {\n        case 'd':\n            return fZ(i + e + l)\n        case 'l':\n            return fZ(i + g + l)\n        case 'r':\n            return fZ(i + g + e)\n        case 'u':\n            return fZ(g + e + l)\n        default:\n            return fZ(i + g + e + l)\n        }\n    }\n}\n\nfunc fI() {\n    g := (11 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] + 4\n    N2[n+1] = N2[n] - a + (a << 16)\n    N3[n+1] = 'd'\n    N4[n+1] = N4[n]\n    cond := Nr[a>>uint(g)] <= N0[n]/4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fG() {\n    g := (19 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] - 4\n    N2[n+1] = N2[n] - a + (a >> 16)\n    N3[n+1] = 'u'\n    N4[n+1] = N4[n]\n    cond := Nr[a>>uint(g)] >= N0[n]/4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fE() {\n    g := (14 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] + 1\n    N2[n+1] = N2[n] - a + (a << 4)\n    N3[n+1] = 'r'\n    N4[n+1] = N4[n]\n    cond := Nc[a>>uint(g)] <= N0[n]%4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fL() {\n    g := (16 - N0[n]) * 4\n    a := N2[n] & uint64(15<<uint(g))\n    N0[n+1] = N0[n] - 1\n    N2[n+1] = N2[n] - a + (a >> 4)\n    N3[n+1] = 'l'\n    N4[n+1] = N4[n]\n    cond := Nc[a>>uint(g)] >= N0[n]%4\n    if !cond {\n        N4[n+1]++\n    }\n    n++\n}\n\nfunc fifteenSolver(n int, g uint64) {\n    N0[0] = n\n    N2[0] = g\n    N4[0] = 0\n}\n\nfunc solve() {\n    if fN() {\n        fmt.Print(\"Solution found in \", n, \" moves: \")\n        for g := 1; g <= n; g++ {\n            fmt.Printf(\"%c\", N3[g])\n        }\n        fmt.Println()\n    } else {\n        n = 0\n        _n++\n        solve()\n    }\n}\n\nfunc main() {\n    fifteenSolver(8, 0xfe169b4c0a73d852)\n    solve()\n}\n"}
{"id": 44633, "name": "Roots of unity", "Python": "import cmath\n\n\nclass Complex(complex):\n    def __repr__(self):\n        rp = '%7.5f' % self.real if not self.pureImag() else ''\n        ip = '%7.5fj' % self.imag if not self.pureReal() else ''\n        conj = '' if (\n            self.pureImag() or self.pureReal() or self.imag < 0.0\n        ) else '+'\n        return '0.0' if (\n            self.pureImag() and self.pureReal()\n        ) else rp + conj + ip\n\n    def pureImag(self):\n        return abs(self.real) < 0.000005\n\n    def pureReal(self):\n        return abs(self.imag) < 0.000005\n\n\ndef croots(n):\n    if n <= 0:\n        return None\n    return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))\n    \n    \n\n\nfor nr in range(2, 11):\n    print(nr, list(croots(nr)))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/cmplx\"\n)\n\nfunc main() {\n    for n := 2; n <= 5; n++ {\n        fmt.Printf(\"%d roots of 1:\\n\", n)\n        for _, r := range roots(n) {\n            fmt.Printf(\"  %18.15f\\n\", r)\n        }\n    }\n}\n\nfunc roots(n int) []complex128 {\n    r := make([]complex128, n)\n    for i := 0; i < n; i++ {\n        r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))\n    }\n    return r\n}\n"}
{"id": 44634, "name": "Long multiplication", "Python": "\nprint 2**64*2**64\n", "Go": "\n\n\n\n\n\n\n\n\npackage main\n\nimport \"fmt\"\n\n\nfunc d(b byte) byte {\n    if b < '0' || b > '9' {\n        panic(\"digit 0-9 expected\")\n    }\n    return b - '0'\n}\n\n\nfunc add(x, y string) string {\n    if len(y) > len(x) {\n        x, y = y, x\n    }\n    b := make([]byte, len(x)+1)\n    var c byte\n    for i := 1; i <= len(x); i++ {\n        if i <= len(y) {\n            c += d(y[len(y)-i])\n        }\n        s := d(x[len(x)-i]) + c\n        c = s / 10\n        b[len(b)-i] = (s % 10) + '0'\n    }\n    if c == 0 {\n        return string(b[1:])\n    }\n    b[0] = c + '0'\n    return string(b)\n}\n\n\nfunc mulDigit(x string, y byte) string {\n    if y == '0' {\n        return \"0\"\n    }\n    y = d(y)\n    b := make([]byte, len(x)+1)\n    var c byte\n    for i := 1; i <= len(x); i++ {\n        s := d(x[len(x)-i])*y + c\n        c = s / 10\n        b[len(b)-i] = (s % 10) + '0'\n    }\n    if c == 0 {\n        return string(b[1:])\n    }\n    b[0] = c + '0'\n    return string(b)\n}\n\n\nfunc mul(x, y string) string {\n    result := mulDigit(x, y[len(y)-1])\n    for i, zeros := 2, \"\"; i <= len(y); i++ {\n        zeros += \"0\"\n        result = add(result, mulDigit(x, y[len(y)-i])+zeros)\n    }\n    return result\n}\n\n\nconst n = \"18446744073709551616\"\n\nfunc main() {\n    fmt.Println(mul(n, n))\n}\n"}
{"id": 44635, "name": "Pell's equation", "Python": "import math\n\ndef solvePell(n):\n    x = int(math.sqrt(n))\n    y, z, r = x, 1, x << 1\n    e1, e2 = 1, 0\n    f1, f2 = 0, 1\n    while True:\n        y = r * z - y\n        z = (n - y * y) // z\n        r = (x + y) // z\n\n        e1, e2 = e2, e1 + e2 * r\n        f1, f2 = f2, f1 + f2 * r\n\n        a, b = f2 * x + e2, f2\n        if a * a - n * b * b == 1:\n            return a, b\n\nfor n in [61, 109, 181, 277]:\n    x, y = solvePell(n)\n    print(\"x^2 - %3d * y^2 = 1 for x = %27d and y = %25d\" % (n, x, y))\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar big1 = new(big.Int).SetUint64(1)\n\nfunc solvePell(nn uint64) (*big.Int, *big.Int) {\n    n := new(big.Int).SetUint64(nn)\n    x := new(big.Int).Set(n)\n    x.Sqrt(x)\n    y := new(big.Int).Set(x)\n    z := new(big.Int).SetUint64(1)\n    r := new(big.Int).Lsh(x, 1)\n\n    e1 := new(big.Int).SetUint64(1)\n    e2 := new(big.Int)\n    f1 := new(big.Int)\n    f2 := new(big.Int).SetUint64(1)\n\n    t := new(big.Int)\n    u := new(big.Int)\n    a := new(big.Int)\n    b := new(big.Int)\n    for {\n        t.Mul(r, z)\n        y.Sub(t, y)\n        t.Mul(y, y)\n        t.Sub(n, t)\n        z.Quo(t, z)\n        t.Add(x, y)\n        r.Quo(t, z)\n        u.Set(e1)\n        e1.Set(e2)\n        t.Mul(r, e2)\n        e2.Add(t, u)\n        u.Set(f1)\n        f1.Set(f2)\n        t.Mul(r, f2)\n        f2.Add(t, u)\n        t.Mul(x, f2)\n        a.Add(e2, t)\n        b.Set(f2)\n        t.Mul(a, a)\n        u.Mul(n, b)\n        u.Mul(u, b)\n        t.Sub(t, u)\n        if t.Cmp(big1) == 0 {\n            return a, b\n        }\n    }\n}\n\nfunc main() {\n    ns := []uint64{61, 109, 181, 277}\n    for _, n := range ns {\n        x, y := solvePell(n)\n        fmt.Printf(\"x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\\n\", n, x, y)\n    }\n}\n"}
{"id": 44636, "name": "Bulls and cows", "Python": "\n\nimport random\n\ndigits = '123456789'\nsize = 4\nchosen = ''.join(random.sample(digits,size))\n\nprint  % (size, size)\nguesses = 0\nwhile True:\n    guesses += 1\n    while True:\n        \n        guess = raw_input('\\nNext guess [%i]: ' % guesses).strip()\n        if len(guess) == size and \\\n           all(char in digits for char in guess) \\\n           and len(set(guess)) == size:\n            break\n        print \"Problem, try again. You need to enter %i unique digits from 1 to 9\" % size\n    if guess == chosen:\n        print '\\nCongratulations you guessed correctly in',guesses,'attempts'\n        break\n    bulls = cows = 0\n    for i in range(size):\n        if guess[i] == chosen[i]:\n            bulls += 1\n        elif guess[i] in chosen:\n            cows += 1\n    print '  %i Bulls\\n  %i Cows' % (bulls, cows)\n", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Println(`Cows and Bulls\nGuess four digit number of unique digits in the range 1 to 9.\nA correct digit but not in the correct place is a cow.\nA correct digit in the correct place is a bull.`)\n    \n    pat := make([]byte, 4)\n    rand.Seed(time.Now().Unix())\n    r := rand.Perm(9)\n    for i := range pat {\n        pat[i] = '1' + byte(r[i])\n    }\n\n    \n    valid := []byte(\"123456789\")\nguess:\n    for in := bufio.NewReader(os.Stdin); ; {\n        fmt.Print(\"Guess: \")\n        guess, err := in.ReadString('\\n')\n        if err != nil {\n            fmt.Println(\"\\nSo, bye.\")\n            return\n        }\n        guess = strings.TrimSpace(guess)\n        if len(guess) != 4 {\n            \n            fmt.Println(\"Please guess a four digit number.\")\n            continue\n        }\n        var cows, bulls int\n        for ig, cg := range guess {\n            if strings.IndexRune(guess[:ig], cg) >= 0 {\n                \n                fmt.Printf(\"Repeated digit: %c\\n\", cg)\n                continue guess\n            }\n            switch bytes.IndexByte(pat, byte(cg)) {\n            case -1:\n                if bytes.IndexByte(valid, byte(cg)) == -1 {\n                    \n                    fmt.Printf(\"Invalid digit: %c\\n\", cg)\n                    continue guess\n                }\n            default: \n                cows++\n            case ig:\n                bulls++\n            }\n        }\n        fmt.Printf(\"Cows: %d, bulls: %d\\n\", cows, bulls)\n        if bulls == 4 {\n            fmt.Println(\"You got it.\")\n            return\n        }\n    }\n}\n"}
{"id": 44637, "name": "Sorting algorithms_Bubble sort", "Python": "def bubble_sort(seq):\n    \n    changed = True\n    while changed:\n        changed = False\n        for i in range(len(seq) - 1):\n            if seq[i] > seq[i+1]:\n                seq[i], seq[i+1] = seq[i+1], seq[i]\n                changed = True\n    return seq\n\nif __name__ == \"__main__\":\n   \n\n   from random import shuffle\n\n   testset = [_ for _ in range(100)]\n   testcase = testset.copy() \n   shuffle(testcase)\n   assert testcase != testset  \n   bubble_sort(testcase)\n   assert testcase == testset  \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    bubblesort(list)\n    fmt.Println(\"sorted!  \", list)\n}\n\nfunc bubblesort(a []int) {\n    for itemCount := len(a) - 1; ; itemCount-- {\n        hasChanged := false\n        for index := 0; index < itemCount; index++ {\n            if a[index] > a[index+1] {\n                a[index], a[index+1] = a[index+1], a[index]\n                hasChanged = true\n            }\n        }\n        if hasChanged == false {\n            break\n        }\n    }\n}\n"}
{"id": 44638, "name": "Product of divisors", "Python": "def product_of_divisors(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans = i = j = 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans *= i\n            j = n//i\n            if j != i:\n                ans *= j\n        i += 1\n    return ans\n    \nif __name__ == \"__main__\":\n    print([product_of_divisors(n) for n in range(1,51)])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc prodDivisors(n int) int {\n    prod := 1\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            prod *= i\n            j := n / i\n            if j != i {\n                prod *= j\n            }\n        }\n        i += k\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The products of positive divisors for the first 50 positive integers are:\")\n    for i := 1; i <= 50; i++ {\n        fmt.Printf(\"%9d  \", prodDivisors(i))\n        if i%5 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 44639, "name": "Product of divisors", "Python": "def product_of_divisors(n):\n    assert(isinstance(n, int) and 0 < n)\n    ans = i = j = 1\n    while i*i <= n:\n        if 0 == n%i:\n            ans *= i\n            j = n//i\n            if j != i:\n                ans *= j\n        i += 1\n    return ans\n    \nif __name__ == \"__main__\":\n    print([product_of_divisors(n) for n in range(1,51)])\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc prodDivisors(n int) int {\n    prod := 1\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            prod *= i\n            j := n / i\n            if j != i {\n                prod *= j\n            }\n        }\n        i += k\n    }\n    return prod\n}\n\nfunc main() {\n    fmt.Println(\"The products of positive divisors for the first 50 positive integers are:\")\n    for i := 1; i <= 50; i++ {\n        fmt.Printf(\"%9d  \", prodDivisors(i))\n        if i%5 == 0 {\n            fmt.Println()\n        }\n    }\n}\n"}
{"id": 44640, "name": "File input_output", "Python": "import shutil\nshutil.copyfile('input.txt', 'output.txt')\n", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"input.txt\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = ioutil.WriteFile(\"output.txt\", b, 0666); err != nil {\n        fmt.Println(err)\n    }\n}\n"}
{"id": 44641, "name": "Arithmetic_Integer", "Python": "x = int(raw_input(\"Number 1: \"))\ny = int(raw_input(\"Number 2: \"))\n\nprint \"Sum: %d\" % (x + y)\nprint \"Difference: %d\" % (x - y)\nprint \"Product: %d\" % (x * y)\nprint \"Quotient: %d\" % (x / y)     \n                                   \nprint \"Remainder: %d\" % (x % y)    \nprint \"Quotient: %d with Remainder: %d\" % divmod(x, y)\nprint \"Power: %d\" % x**y\n\n\nraw_input( )\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a, b int\n    fmt.Print(\"enter two integers: \")\n    fmt.Scanln(&a, &b)\n    fmt.Printf(\"%d + %d = %d\\n\", a, b, a+b)\n    fmt.Printf(\"%d - %d = %d\\n\", a, b, a-b)\n    fmt.Printf(\"%d * %d = %d\\n\", a, b, a*b)\n    fmt.Printf(\"%d / %d = %d\\n\", a, b, a/b)  \n    fmt.Printf(\"%d %% %d = %d\\n\", a, b, a%b) \n    \n}\n"}
{"id": 44642, "name": "Matrix transposition", "Python": "m=((1,  1,  1,   1),\n   (2,  4,  8,  16),\n   (3,  9, 27,  81),\n   (4, 16, 64, 256),\n   (5, 25,125, 625))\nprint(zip(*m))\n\n\n", "Go": "package main\n\nimport (\n    \"fmt\"\n\n    \"gonum.org/v1/gonum/mat\"\n)\n\nfunc main() {\n    m := mat.NewDense(2, 3, []float64{\n        1, 2, 3,\n        4, 5, 6,\n    })\n    fmt.Println(mat.Formatted(m))\n    fmt.Println()\n    fmt.Println(mat.Formatted(m.T()))\n}\n"}
{"id": 44643, "name": "Man or boy test", "Python": "\nimport sys\nsys.setrecursionlimit(1025)\n\ndef a(in_k, x1, x2, x3, x4, x5):\n    k = [in_k]\n    def b():\n        k[0] -= 1\n        return a(k[0], b, x1, x2, x3, x4)\n    return x4() + x5() if k[0] <= 0 else b()\n\nx = lambda i: lambda: i\nprint(a(10, x(1), x(-1), x(-1), x(1), x(0)))\n", "Go": "package main\nimport \"fmt\"\n\nfunc a(k int, x1, x2, x3, x4, x5 func() int) int {\n\tvar b func() int\n\tb = func() int {\n\t\tk--\n\t\treturn a(k, b, x1, x2, x3, x4)\n\t}\n\tif k <= 0 {\n\t\treturn x4() + x5()\n\t}\n\treturn b()\n}\n\nfunc main() {\n\tx := func(i int) func() int { return func() int { return i } }\n\tfmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))\n}\n"}
{"id": 44644, "name": "Short-circuit evaluation", "Python": ">>> def a(answer):\n\tprint(\"  \n\treturn answer\n\n>>> def b(answer):\n\tprint(\"  \n\treturn answer\n\n>>> for i in (False, True):\n\tfor j in (False, True):\n\t\tprint (\"\\nCalculating: x = a(i) and b(j)\")\n\t\tx = a(i) and b(j)\n\t\tprint (\"Calculating: y = a(i) or  b(j)\")\n\t\ty = a(i) or  b(j)\n\n\t\t\n\nCalculating: x = a(i) and b(j)\n  \nCalculating: y = a(i) or  b(j)\n  \n  \n\nCalculating: x = a(i) and b(j)\n  \nCalculating: y = a(i) or  b(j)\n  \n  \n\nCalculating: x = a(i) and b(j)\n  \n  \nCalculating: y = a(i) or  b(j)\n  \n\nCalculating: x = a(i) and b(j)\n  \n  \nCalculating: y = a(i) or  b(j)\n  \n", "Go": "package main\n\nimport \"fmt\"\n\nfunc a(v bool) bool {\n    fmt.Print(\"a\")\n    return v\n}\n\nfunc b(v bool) bool {\n    fmt.Print(\"b\")\n    return v\n}\n\nfunc test(i, j bool) {\n    fmt.Printf(\"Testing a(%t) && b(%t)\\n\", i, j)\n    fmt.Print(\"Trace:  \")\n    fmt.Println(\"\\nResult:\", a(i) && b(j))\n\n    fmt.Printf(\"Testing a(%t) || b(%t)\\n\", i, j)\n    fmt.Print(\"Trace:  \")\n    fmt.Println(\"\\nResult:\", a(i) || b(j))\n\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    test(false, false)\n    test(false, true)\n    test(true, false)\n    test(true, true)\n}\n"}
{"id": 44645, "name": "Find limit of recursion", "Python": "import sys\nprint(sys.getrecursionlimit())\n", "Go": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"runtime/debug\"\n)\n\nfunc main() {\n\tstack := flag.Int(\"stack\", 0, \"maximum per goroutine stack size or 0 for the default\")\n\tflag.Parse()\n\tif *stack > 0 {\n\t\tdebug.SetMaxStack(*stack)\n\t}\n\tr(1)\n}\n\nfunc r(l int) {\n\tif l%1000 == 0 {\n\t\tfmt.Println(l)\n\t}\n\tr(l + 1)\n}\n"}
{"id": 44646, "name": "Bitwise operations", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n", "C++": "#include <iostream>\n\nvoid bitwise(int a, int b)\n{\n  std::cout << \"a and b: \" << (a & b)  << '\\n'; \n  std::cout << \"a or b:  \" << (a | b)  << '\\n';\n  std::cout << \"a xor b: \" << (a ^ b)  << '\\n';\n  std::cout << \"not a:   \" << ~a       << '\\n';\n\n  \n  \n  std::cout << \"a shl b: \" << (a << b) << '\\n'; \n  std::cout << \"a shr b: \" << (a >> b) << '\\n'; \n  unsigned int ua = a;\n  std::cout << \"a lsr b: \" << (ua >> b) << '\\n'; \n\n  \n  \n  \n  std::cout << \"a rol b: \" << std::rotl(ua, b) << '\\n';\n  std::cout << \"a ror b: \" << std::rotr(ua, b) << '\\n';\n  \n}\n"}
{"id": 44647, "name": "Dragon curve", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n", "C++": "#include <windows.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c )\n    {\n\tclr = c; createPen();\n    }\n\n    void setPenWidth( int w )\n    {\n\twid = w; createPen();\n    }\n\n    void saveBitmap( string path )\n     {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass dragonC\n{\npublic:\n    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n    void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n    void generate( int it )\n    {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t    temp = generator; temp.push_back( 1 );\n\t    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t    generator = temp;\n\t}\n    }\n\n    void draw()\n    {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];\n\t    MoveToEx( dc, a, b, NULL );\n\n\t    bmp.setPenColor( clr[t] );\n\t    for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t    {\n\t\tswitch( dir )\n\t\t{\n\t\t    case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t    break;\n\t\t    case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t    break;\n\t\t    case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t    break;\n\t\t    case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t        LineTo( dc, a, b );\n\t    }\n\t}\n\t\n\tbmp.saveBitmap( \"f:/rc/dragonCpp.bmp\" );\n    }\n\t\n    int dir;\n    myBitmap bmp;\n    string generator;\n};\n\nint main( int argc, char* argv[] )\n{\n    dragonC d; d.draw( 17 );\n    return system( \"pause\" );\n}\n\n"}
{"id": 44648, "name": "Read a file line by line", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n", "C++": "#include <fstream>\n#include <string>\n#include <iostream>\n\nint main( int argc , char** argv ) {\n   int linecount = 0 ;\n   std::string line  ;\n   std::ifstream infile( argv[ 1 ] ) ; \n   if ( infile ) {\n      while ( getline( infile , line ) ) {\n\t std::cout << linecount << \": \" \n                   << line      << '\\n' ;  \n\t linecount++ ;\n      }\n   }\n   infile.close( ) ;\n   return 0 ;\n}\n"}
{"id": 44649, "name": "Doubly-linked list_Element insertion", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n", "C++": "template <typename T>\nvoid insert_after(Node<T>* N, T&& data)\n{\n    auto node = new Node<T>{N, N->next, std::forward(data)};\n    if(N->next != nullptr)\n        N->next->prev = node;\n    N->next = node;\n}\n"}
{"id": 44650, "name": "Quickselect algorithm", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n", "C++": "#include <algorithm>\n#include <iostream>\n\nint main() {\n  for (int i = 0; i < 10; i++) {\n    int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n    std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));\n    std::cout << a[i];\n    if (i < 9) std::cout << \", \";\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 44651, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "C++": "#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <cassert>\n\nstd::string const digits = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_base(unsigned long num, int base)\n{\n  if (num == 0)\n    return \"0\";\n  \n  std::string result;\n  while (num > 0) {\n    std::ldiv_t temp = std::div(num, (long)base);\n    result += digits[temp.rem];\n    num = temp.quot;\n  }\n  std::reverse(result.begin(), result.end());\n  return result;\n}\n\nunsigned long from_base(std::string const& num_str, int base)\n{\n  unsigned long result = 0;\n  for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)\n    result = result * base + digits.find(num_str[pos]);\n  return result;\n}\n"}
{"id": 44652, "name": "Walk a directory_Recursively", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n", "C++": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n  path current_dir(\".\"); \n  boost::regex pattern(\"a.*\"); \n  for (recursive_directory_iterator iter(current_dir), end;\n       iter != end;\n       ++iter)\n  {\n    std::string name = iter->path().filename().string();\n    if (regex_match(name, pattern))\n      std::cout << iter->path() << \"\\n\";\n  }\n}\n"}
{"id": 44653, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "C++": "#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <numeric>\n\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n\nstd::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept\n{\n  auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};\n  \n  \n  \n  struct byte_checksum\n  {\n    std::uint_fast32_t operator()() noexcept\n    {\n      auto checksum = static_cast<std::uint_fast32_t>(n++);\n      \n      for (auto i = 0; i < 8; ++i)\n        checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);\n      \n      return checksum;\n    }\n    \n    unsigned n = 0;\n  };\n  \n  auto table = std::array<std::uint_fast32_t, 256>{};\n  std::generate(table.begin(), table.end(), byte_checksum{});\n  \n  return table;\n}\n\n\n\ntemplate <typename InputIterator>\nstd::uint_fast32_t crc(InputIterator first, InputIterator last)\n{\n  \n  static auto const table = generate_crc_lookup_table();\n  \n  \n  \n  return std::uint_fast32_t{0xFFFFFFFFuL} &\n    ~std::accumulate(first, last,\n      ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},\n        [](std::uint_fast32_t checksum, std::uint_fast8_t value) \n          { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });\n}\n\nint main()\n{\n  auto const s = std::string{\"The quick brown fox jumps over the lazy dog\"};\n  \n  std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\\n';\n}\n"}
{"id": 44654, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 44655, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 44656, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "C++": "#include <string>\n#include <boost/regex.hpp>\n#include <iostream>\n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n   std::string text = \"Character,Speech\\n\" \n                            \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t    \"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\\n\" \n\t                    \"The multitude,Who are you?\\n\" \n\t\t            \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t            \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n  std::cout << csvToHTML( text ) ;\n  return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n   \n   std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n   const char* replacements [ 5 ] = { \"&lt;\" , \"&gt;\" , \"    <TR><TD>$1\" , \"</TD><TD>\", \"</TD></TR>\\n\"  } ;  \n   boost::regex e1( regexes[ 0 ] ) ; \n   std::string tabletext = boost::regex_replace( csvtext , e1 ,\n     replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n   for ( int i = 1 ; i < 5 ; i++ ) {\n      e1.assign( regexes[ i ] ) ;\n      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n   }\n   tabletext = std::string( \"<TABLE>\\n\" ) + tabletext ;\n   tabletext.append( \"</TABLE>\\n\" ) ;\n   return tabletext ;\n}\n"}
{"id": 44657, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "C++": "PRAGMA COMPILER g++\nPRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive\n\nOPTION PARSE FALSE\n\n\n'---The class does the declaring for you\n\nCLASS Books \n\tpublic: \n\t\tconst char* title;\n\t\tconst char* author; \n\t\tconst char* subject; \n\t\tint book_id; \nEND CLASS\n\n\n'---pointer to an object declaration (we use a class called Books) \nDECLARE Book1 TYPE Books\n'--- the correct syntax for class\nBook1  =  Books()\n\n\n'--- initialize the strings const char* in c++\nBook1.title = \"C++ Programming to bacon \"\nBook1.author = \"anyone\"\nBook1.subject =\"RECORD Tutorial\"\nBook1.book_id = 1234567\n\n\nPRINT \"Book title   : \" ,Book1.title FORMAT \"%s%s\\n\"\nPRINT \"Book author  : \", Book1.author FORMAT \"%s%s\\n\"\nPRINT \"Book subject : \", Book1.subject FORMAT \"%s%s\\n\"\nPRINT \"Book book_id : \", Book1.book_id FORMAT \"%s%d\\n\"\n"}
{"id": 44658, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 44659, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n\nlong string2long( const std::string & s ) {\n   long result ;\n   std::istringstream( s ) >> result ;\n   return result ;\n}\n\nbool isKaprekar( long number ) {\n   long long squarenumber = ((long long)number) * number ;\n   std::ostringstream numberbuf ;\n   numberbuf << squarenumber ;\n   std::string numberstring = numberbuf.str( ) ;\n   for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n      std::string firstpart = numberstring.substr( 0 , i ) ,\n                  secondpart = numberstring.substr( i ) ;\n      \n      if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n      }\n      if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n      }\n   }\n   return false ;\n}\n\nint main( ) {\n   std::vector<long> kaprekarnumbers ;\n   kaprekarnumbers.push_back( 1 ) ;\n   for ( int i = 2 ; i < 1000001 ; i++ ) {\n      if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n   }\n   std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;\n   std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n   while ( *svi < 10000 ) {\n      std::cout << *svi << \" \" ;\n      svi++ ;\n   }\n   std::cout << '\\n' ;\n   std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n   std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator<long>( std::cout , \"\\n\" ) ) ;\n   std::cout << \"There are \" << kaprekarnumbers.size( )\n      << \" Kaprekar numbers less than one million!\\n\" ;\n   return 0 ;\n}\n"}
{"id": 44660, "name": "LZW compression", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n", "C++": "#include <string>\n#include <map>\n\n\n\n\ntemplate <typename Iterator>\nIterator compress(const std::string &uncompressed, Iterator result) {\n  \n  int dictSize = 256;\n  std::map<std::string,int> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[std::string(1, i)] = i;\n  \n  std::string w;\n  for (std::string::const_iterator it = uncompressed.begin();\n       it != uncompressed.end(); ++it) {\n    char c = *it;\n    std::string wc = w + c;\n    if (dictionary.count(wc))\n      w = wc;\n    else {\n      *result++ = dictionary[w];\n      \n      dictionary[wc] = dictSize++;\n      w = std::string(1, c);\n    }\n  }\n  \n  \n  if (!w.empty())\n    *result++ = dictionary[w];\n  return result;\n}\n\n\n\ntemplate <typename Iterator>\nstd::string decompress(Iterator begin, Iterator end) {\n  \n  int dictSize = 256;\n  std::map<int,std::string> dictionary;\n  for (int i = 0; i < 256; i++)\n    dictionary[i] = std::string(1, i);\n  \n  std::string w(1, *begin++);\n  std::string result = w;\n  std::string entry;\n  for ( ; begin != end; begin++) {\n    int k = *begin;\n    if (dictionary.count(k))\n      entry = dictionary[k];\n    else if (k == dictSize)\n      entry = w + w[0];\n    else\n      throw \"Bad compressed k\";\n    \n    result += entry;\n    \n    \n    dictionary[dictSize++] = w + entry[0];\n    \n    w = entry;\n  }\n  return result;\n}\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nint main() {\n  std::vector<int> compressed;\n  compress(\"TOBEORNOTTOBEORTOBEORNOT\", std::back_inserter(compressed));\n  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, \", \"));\n  std::cout << std::endl;\n  std::string decompressed = decompress(compressed.begin(), compressed.end());\n  std::cout << decompressed << std::endl;\n  \n  return 0;\n}\n"}
{"id": 44661, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 44662, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "C++": "#include <iomanip>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n    auto n = rlistSize > slistSize ? rlistSize : slistSize;\n    auto rlist = new vector<unsigned> { 1, 3, 7 };\n    auto slist = new vector<unsigned> { 2, 4, 5, 6 };\n    auto list = rlistSize > 0 ? rlist : slist;\n    auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n    while (list->size() > target_size) list->pop_back();\n\n    while (list->size() < target_size)\n    {\n        auto lastIndex = rlist->size() - 1;\n        auto lastr = (*rlist)[lastIndex];\n        auto r = lastr + (*slist)[lastIndex];\n        rlist->push_back(r);\n        for (auto s = lastr + 1; s < r && list->size() < target_size;)\n            slist->push_back(s++);\n    }\n\n    auto v = (*list)[n - 1];\n    delete rlist;\n    delete slist;\n    return v;\n}\n\nostream& operator<<(ostream& os, const set<unsigned>& s)\n{\n    cout << '(' << s.size() << \"):\";\n    auto i = 0;\n    for (auto c = s.begin(); c != s.end();)\n    {\n        if (i++ % 20 == 0) os << endl;\n        os << setw(5) << *c++;\n    }\n    return os;\n}\n\nint main(int argc, const char* argv[])\n{\n    const auto v1 = atoi(argv[1]);\n    const auto v2 = atoi(argv[2]);\n    set<unsigned> r, s;\n    for (auto n = 1; n <= v2; n++)\n    {\n        if (n <= v1)\n            r.insert(hofstadter(n, 0));\n        s.insert(hofstadter(0, n));\n    }\n    cout << \"R\" << r << endl;\n    cout << \"S\" << s << endl;\n\n    int m = max(*r.rbegin(), *s.rbegin());\n    for (auto n = 1; n <= m; n++)\n        if (r.count(n) == s.count(n))\n            clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n    return 0;\n}\n"}
{"id": 44663, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 44664, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 44665, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "C++": "#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n    MagicSquare(int d) : sqr(d*d,0), sz(d)\n    {\n        assert(d&1);\n        fillSqr();\n    }\n \n    void display()\n    {\n        cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n        cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n        ostringstream cvr;\n        cvr << sz * sz;\n        int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t    int yy = y * sz;\n\t    for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t    cout << \"\\n\";\n\t}\n        cout << \"\\n\\n\";\n    }\n \nprivate:\n    void fillSqr()\n    {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t    if( !sqr[sx + sy * sz] )\n\t    {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t    }\n\t    else\n\t    {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t    }\n\t}\n    }\n \n    int magicNumber()\n    { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n    void inc( int& a )\n    { if( ++a == sz ) a = 0; }\n \n    void dec( int& a )\n    { if( --a < 0 ) a = sz - 1; }\n \n    bool checkPos( int x, int y )\n    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n    bool isInside( int s )\n    { return ( s < sz && s > -1 ); }\n \n    vector<int> sqr;\n    int sz;\n};\n \nint main()\n{\n    MagicSquare s(7);\n    s.display();\n    return 0;\n}\n"}
{"id": 44666, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 44667, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "C++": "\n\n#include <cln/integer.h>\n#include <cln/integer_io.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <map>\nusing namespace cln ;\n\nclass NextNum {\npublic :\n   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n   cl_I operator( )( ) {\n      cl_I result = first + second ;\n      first = second ;\n      second = result ;\n      return result ;\n   }\nprivate :\n   cl_I first ;\n   cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {\n   for ( cl_I bignumber : fibos ) {\n      std::ostringstream os ;\n      fprintdecimal ( os , bignumber ) ;\n      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n      if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n   }\n}\n\nint main( ) {\n   std::vector<cl_I> fibonaccis( 1000 ) ;\n   fibonaccis[ 0 ] = 0 ;\n   fibonaccis[ 1 ] = 1 ;\n   cl_I a = 0 ;\n   cl_I b = 1 ;\n   \n   \n   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n   std::cout << std::endl ;\n   std::map<int , int> frequencies ;\n   findFrequencies( fibonaccis , frequencies ) ;\n   std::cout << \"                found                    expected\\n\" ;\n   for ( int i = 1 ; i < 10 ; i++ ) {\n      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;\n      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;\n      std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n      std::cout.precision( 3 ) ;\n      std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 44668, "name": "Anonymous recursion", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n", "C++": "double fib(double n)\n{\n  if(n < 0)\n  {\n    throw \"Invalid argument passed to fib\";\n  }\n  else\n  {\n    struct actual_fib\n    {\n        static double calc(double n)\n        {\n          if(n < 2)\n          {\n            return n;\n          }\n          else\n          {\n            return calc(n-1) + calc(n-2);\n          }\n        }\n    };\n\n    return actual_fib::calc(n);\n  }\n}\n"}
{"id": 44669, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 44670, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 44671, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "C++": "#include <string>\n#include <iostream>\n\nint main( ) {\n   std::string word( \"Premier League\" ) ;\n   std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n   std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n   std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n   return 0 ;\n}\n"}
{"id": 44672, "name": "Longest string challenge", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n", "C++": "#include <iostream>\n#include <string.h>\n \nint main()\n{\n    std::string longLine, longestLines, newLine;\n\n    while (std::cin >> newLine)\n    {\n        auto isNewLineShorter = longLine.c_str();\n        auto isLongLineShorter = newLine.c_str(); \n        while (*isNewLineShorter && *isLongLineShorter)\n        {\n            \n            \n            \n            isNewLineShorter = &isNewLineShorter[1];\n            isLongLineShorter = &isLongLineShorter[1];\n        }\n\n        if(*isNewLineShorter) continue; \n        if(*isLongLineShorter)\n        {\n            \n            longLine = newLine;\n            longestLines = newLine;\n        }\n        else\n        {\n            \n            longestLines+=newLine; \n        }\n        longestLines+=\"\\n\"; \n    }\n\n    std::cout << \"\\nLongest string:\\n\" << longestLines;\n}\n"}
{"id": 44673, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 44674, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n\nstruct action { char write, direction; };\n\nclass tape\n{\npublic:\n    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n    void reset() { clear( '0' ); headPos = _sp; }\n    char read(){ return _t[headPos]; }\n    void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n    void action( const action* a ) { write( a->write ); move( a->direction ); }\n    void print( int c = 10 ) \n    {\n\tint ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n    }\nprivate:\n    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n\nclass state\n{\npublic:\n    bool operator ==( const string o ) { return o == name; }\n    string name, next; char symbol, write, direction;\n};\n\nclass actionTable\n{\npublic:\n    bool loadTable( string file )\n    {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t    string str; state stt;\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t    }\n\t    while( mf.good() )\n\t    {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t    }\n\t    mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n    }\n\n    bool action( char symbol, action& a )\n    {\n\tvector<state>::iterator f = states.begin();\n\twhile( true )\n\t{\n\t    f = find( f, states.end(), curState );\n\t    if( f == states.end() ) return false;\n\t    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t    f++;\n\t}\n\treturn true;\n    }\n    void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n    string getInput() { return input; }\n    char getBlank() { return blank; }\nprivate:\n    void parseState( string str, state& stt )\n    {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n    }\n    vector<state> states; char blank; string curState, input;\n};\n\nclass utm\n{\npublic:\n    utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n    void start()\n    {\n\twhile( true )\n\t{\n\t    reset(); int t = showMenu(); if( t == 0 ) return;\n\t    if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n    }\nprivate:\n    void simulate()\n    {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n    }\n\n    int showMenu()\n    {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t    system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t    cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n    }\n\n    void reset() { tp.reset(); at.reset(); }\n    void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n    tape tp; actionTable at; string files[7];\n};\n\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n\n"}
{"id": 44675, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "C++": "#include <direct.h>\n#include <fstream>\n\nint main() {\n    std::fstream f(\"output.txt\", std::ios::out);\n    f.close();\n    f.open(\"/output.txt\", std::ios::out);\n    f.close();\n\n    _mkdir(\"docs\");\n    _mkdir(\"/docs\");\n\n    return 0;\n}\n"}
{"id": 44676, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 44677, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "C++": "#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n                                \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n                                \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n                                \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n                                \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n                                \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n                                \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n                                \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n                                \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n                                \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n        \n        for (auto elm : dna) {\n            if (count.find(elm) == count.end())\n                count[elm] = 0;\n            ++count[elm];\n        }\n    }\n\n    void viewGenome() {\n        std::cout << \"Sequence:\" << std::endl;\n        std::cout << std::endl;\n        int limit = genome.size() / displayWidth;\n        if (genome.size() % displayWidth != 0)\n            ++limit;\n\n        for (int i = 0; i < limit; ++i) {\n            int beginPos = i * displayWidth;\n            std::cout << std::setw(4) << beginPos << \"  :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n        }\n        std::cout << std::endl;\n        std::cout << \"Base Count\" << std::endl;\n        std::cout << \"----------\" << std::endl;\n        std::cout << std::endl;\n        int total = 0;\n        for (auto elm : count) {\n            std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n            total += elm.second;\n        }\n        std::cout << std::endl;\n        std::cout << \"Total: \" << total << std::endl;\n    }\n\nprivate:\n    std::string genome;\n    std::map<char, int> count;\n    int displayWidth;\n};\n\nint main(void) {\n    auto d = new DnaBase();\n    d->viewGenome();\n    delete d;\n    return 0;\n}\n"}
{"id": 44678, "name": "Dining philosophers", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n", "C++": "#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <mutex>\n#include <random>\n#include <string>\n#include <string_view>\n#include <thread>\n\nconst int timeScale = 42;  \n\nvoid Message(std::string_view message)\n{\n    \n    static std::mutex cout_mutex;\n    std::scoped_lock cout_lock(cout_mutex);\n    std::cout << message << std::endl;\n}\n\nstruct Fork {\n    std::mutex mutex;\n};\n\nstruct Dinner {\n    std::array<Fork, 5> forks;\n    ~Dinner() { Message(\"Dinner is over\"); }\n};\n\nclass Philosopher\n{\n    \n    \n    std::mt19937 rng{std::random_device {}()};\n\n    const std::string name;\n    Fork& left;\n    Fork& right;\n    std::thread worker;\n\n    void live();\n    void dine();\n    void ponder();\npublic:\n    Philosopher(std::string name_, Fork& l, Fork& r)\n    : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)\n    {}\n    ~Philosopher()\n    {\n        worker.join();\n        Message(name + \" went to sleep.\");\n    }\n};\n\nvoid Philosopher::live()\n{\n    for(;;) \n    {\n        {\n            \n            \n            std::scoped_lock dine_lock(left.mutex, right.mutex);\n\n            dine();\n\n            \n        }\n        \n        ponder();\n    }\n}\n\nvoid Philosopher::dine()\n{\n    Message(name + \" started eating.\");\n\n    \n    thread_local std::array<const char*, 3> foods {\"chicken\", \"rice\", \"soda\"};\n    thread_local std::array<const char*, 3> reactions {\n        \"I like this %s!\", \"This %s is good.\", \"Mmm, %s...\"\n    };\n    thread_local std::uniform_int_distribution<> dist(1, 6);\n    std::shuffle(    foods.begin(),     foods.end(), rng);\n    std::shuffle(reactions.begin(), reactions.end(), rng);\n    \n    constexpr size_t buf_size = 64;\n    char buffer[buf_size];\n    for(int i = 0; i < 3; ++i) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));\n        snprintf(buffer, buf_size, reactions[i], foods[i]);\n        Message(name + \": \" + buffer);\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);\n\n    Message(name + \" finished and left.\");\n}\n\nvoid Philosopher::ponder()\n{\n    static constexpr std::array<const char*, 5> topics {{\n        \"politics\", \"art\", \"meaning of life\", \"source of morality\", \"how many straws makes a bale\"\n    }};\n    thread_local std::uniform_int_distribution<> wait(1, 6);\n    thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);\n    while(dist(rng) > 0) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n        Message(name + \" is pondering about \" + topics[dist(rng)] + \".\");\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));\n    Message(name + \" is hungry again!\");\n}\n\nint main()\n{\n    Dinner dinner;\n    Message(\"Dinner started!\");\n    \n    std::array<Philosopher, 5> philosophers {{\n            {\"Aristotle\",   dinner.forks[0], dinner.forks[1]},\n            {\"Democritus\",  dinner.forks[1], dinner.forks[2]},\n            {\"Plato\",       dinner.forks[2], dinner.forks[3]},\n            {\"Pythagoras\",  dinner.forks[3], dinner.forks[4]},\n            {\"Socrates\",    dinner.forks[4], dinner.forks[0]},\n    }};\n    Message(\"It is dark outside...\");\n}\n"}
{"id": 44679, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 44680, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "C++": "#include <iostream>\n\nclass factorion_t {\npublic:\n    factorion_t() {\n        f[0] = 1u;\n        for (uint n = 1u; n < 12u; n++)\n            f[n] = f[n - 1] * n;\n    }\n\n    bool operator()(uint i, uint b) const {\n        uint sum = 0;\n        for (uint j = i; j > 0u; j /= b)\n            sum += f[j % b];\n        return sum == i;\n    }\n\nprivate:\n    ulong f[12];  \n};\n\nint main() {\n    factorion_t factorion;\n    for (uint b = 9u; b <= 12u; ++b) {\n        std::cout << \"factorions for base \" << b << ':';\n        for (uint i = 1u; i < 1500000u; ++i)\n            if (factorion(i, b))\n                std::cout << ' ' << i;\n        std::cout << std::endl;\n    }\n    return 0;\n}\n"}
{"id": 44681, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 44682, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n    size_t len = 0, n = str.length();\n    while (len < n && std::isupper(static_cast<unsigned char>(str[len])))\n        ++len;\n    return len;\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::vector<command> commands;\n    std::istringstream is(table);\n    std::string word;\n    while (is >> word) {\n        \n        size_t len = get_min_length(word);\n        \n        uppercase(word);\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 44683, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 44684, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <bitset>\n#include <string>\n\nclass bacon {\npublic:\n    bacon() {\n        int x = 0;\n        for( ; x < 9; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 20; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n        bAlphabet.push_back( bAlphabet.back() );\n        \n        for( ; x < 24; x++ )\n            bAlphabet.push_back( std::bitset<5>( x ).to_string() );\n    }\n\n    std::string encode( std::string txt ) {\n        std::string r;\n        size_t z;\n        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {\n            z = toupper( *i );\n            if( z < 'A' || z > 'Z' ) continue;\n            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );\n        }\n        return r;\n    }\n\n    std::string decode( std::string txt ) {\n        size_t len = txt.length();\n        while( len % 5 != 0 ) len--;\n        if( len != txt.length() ) txt = txt.substr( 0, len );\n        std::string r;\n        for( size_t i = 0; i < len; i += 5 ) {\n            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );\n        }\n        return r;\n    }\n\nprivate:\n    std::vector<std::string> bAlphabet;\n};\n"}
{"id": 44685, "name": "Spiral matrix", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n", "C++": "#include <vector>\n#include <memory>\t\n#include <cmath>\t\n#include <iostream>\n#include <iomanip>\t\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getSpiralArray( int dimension )\n{\n\tauto_ptr< IntTable > spiralArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\tint numConcentricSquares = static_cast< int >( ceil(\n\t\tstatic_cast< double >( dimension ) / 2.0 ) );\n\n\tint j;\n\tint sideLen = dimension;\n\tint currNum = 0;\n\n\tfor ( int i = 0; i < numConcentricSquares; i++ )\n\t{\n\t\t\n\t\tfor ( j = 0; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = 1; j < sideLen; j++ )\n\t\t\t( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > -1; j-- )\n\t\t\t( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;\n\n\t\t\n\t\tfor ( j = sideLen - 2; j > 0; j-- )\n\t\t\t( *spiralArrayPtr )[ i + j ][ i ] = currNum++;\n\n\t\tsideLen -= 2;\n\t}\n\n\treturn spiralArrayPtr;\n}\n\nvoid printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )\n{\n\tsize_t dimension = spiralArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintSpiralArray( getSpiralArray( 5 ) );\n}\n"}
{"id": 44686, "name": "Optional parameters", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n", "C++": "#include <vector>\n#include <algorithm>\n#include <string>\n\n\ntemplate <class T>\nstruct sort_table_functor {\n  typedef bool (*CompFun)(const T &, const T &);\n  const CompFun ordering;\n  const int column;\n  const bool reverse;\n  sort_table_functor(CompFun o, int c, bool r) :\n    ordering(o), column(c), reverse(r) { }\n  bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {\n    const T &a = x[column],\n            &b = y[column];\n    return reverse ? ordering(b, a)\n                   : ordering(a, b);\n  }\n};\n\n\ntemplate <class T>\nbool myLess(const T &x, const T &y) { return x < y; }\n\n\ntemplate <class T>\nvoid sort_table(std::vector<std::vector<T> > &table,\n                int column = 0, bool reverse = false,\n                bool (*ordering)(const T &, const T &) = myLess) {\n  std::sort(table.begin(), table.end(),\n            sort_table_functor<T>(ordering, column, reverse));\n}\n\n#include <iostream>\n\n\ntemplate <class T>\nvoid print_matrix(std::vector<std::vector<T> > &data) {\n  for () {\n    for (int j = 0; j < 3; j++)\n      std::cout << data[i][j] << \"\\t\";\n    std::cout << std::endl;\n  }\n}\n\n\nbool desc_len_comparator(const std::string &x, const std::string &y) {\n  return x.length() > y.length();\n}\n\nint main() {\n\n  std::string data_array[3][3] =\n    {\n      {\"a\", \"b\", \"c\"},\n      {\"\", \"q\", \"z\"},\n      {\"zap\", \"zip\", \"Zot\"}\n    };\n\n  std::vector<std::vector<std::string> > data_orig;\n  for (int i = 0; i < 3; i++) {\n    std::vector<std::string> row;\n    for (int j = 0; j < 3; j++)\n      row.push_back(data_array[i][j]);\n    data_orig.push_back(row);\n  }\n  print_matrix(data_orig);\n\n  std::vector<std::vector<std::string> > data = data_orig;\n  sort_table(data);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 2);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 1, true);\n  print_matrix(data);\n\n  data = data_orig;\n  sort_table(data, 0, false, desc_len_comparator);\n  print_matrix(data);\n\n  return 0;\n}\n"}
{"id": 44687, "name": "Call a foreign-language function", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n"}
{"id": 44688, "name": "Call a foreign-language function", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n", "C++": "FUNCTION MULTIPLY(X, Y)\nDOUBLE PRECISION MULTIPLY, X, Y\n"}
{"id": 44689, "name": "Faulhaber's triangle", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <vector>\n \nclass Frac {\npublic:\n\n\tFrac() : num(0), denom(1) {}\n\n\tFrac(int n, int d) {\n\t\tif (d == 0) {\n\t\t\tthrow std::runtime_error(\"d must not be zero\");\n\t\t}\n\n\t\tint sign_of_d = d < 0 ? -1 : 1;\n\t\tint g = std::gcd(n, d);\n\n        num = sign_of_d * n / g;\n        denom = sign_of_d * d / g;\n\t}\n \n\tFrac operator-() const {\n\t\treturn Frac(-num, denom);\n\t}\n \n\tFrac operator+(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator-(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);\n\t}\n \n\tFrac operator*(const Frac& rhs) const {\n\t\treturn Frac(num*rhs.num, denom*rhs.denom);\n\t}\n\n\tFrac operator*(int rhs) const {\n\t\treturn Frac(num * rhs, denom);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Frac&);\n \nprivate:\n\tint num;\n\tint denom;\n};\n \nstd::ostream & operator<<(std::ostream & os, const Frac &f) {\n\tif (f.num == 0 || f.denom == 1) {\n\t\treturn os << f.num;\n\t}\n \n\tstd::stringstream ss;\n\tss << f.num << \"/\" << f.denom;\n\treturn os << ss.str();\n}\n \nFrac bernoulli(int n) {\n\tif (n < 0) {\n\t\tthrow std::runtime_error(\"n may not be negative or zero\");\n\t}\n \n\tstd::vector<Frac> a;\n\tfor (int m = 0; m <= n; m++) {\n\t\ta.push_back(Frac(1, m + 1));\n\t\tfor (int j = m; j >= 1; j--) {\n\t\t\ta[j - 1] = (a[j - 1] - a[j]) * j;\n\t\t}\n\t}\n \n\t\n\tif (n != 1) return a[0];\n\treturn -a[0];\n}\n \nint binomial(int n, int k) {\n\tif (n < 0 || k < 0 || n < k) {\n\t\tthrow std::runtime_error(\"parameters are invalid\");\n\t}\n\tif (n == 0 || k == 0) return 1;\n \n\tint num = 1;\n\tfor (int i = k + 1; i <= n; i++) {\n\t\tnum *= i;\n\t}\n \n\tint denom = 1;\n\tfor (int i = 2; i <= n - k; i++) {\n\t\tdenom *= i;\n\t}\n \n\treturn num / denom;\n}\n \nstd::vector<Frac> faulhaberTraingle(int p) {\n\tstd::vector<Frac> coeffs(p + 1);\n \n\tFrac q{ 1, p + 1 };\n\tint sign = -1;\n\tfor (int j = 0; j <= p; j++) {\n\t\tsign *= -1;\n\t\tcoeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);\n\t}\n \n\treturn coeffs;\n}\n \nint main() {\n \n\tfor (int i = 0; i < 10; i++) {\n\t\tstd::vector<Frac> coeffs = faulhaberTraingle(i);\n\t\tfor (auto frac : coeffs) {\n\t\t\tstd::cout << std::right << std::setw(5) << frac << \"  \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n \n\treturn 0;\n}\n"}
{"id": 44690, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 44691, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "C++": "#include <iostream>\n\nint main(int argc, char* argv[])\n{\n  std::cout << \"This program is named \" << argv[0] << std::endl;\n  std::cout << \"There are \" << argc-1 << \" arguments given.\" << std::endl;\n  for (int i = 1; i < argc; ++i)\n    std::cout << \"the argument #\" << i << \" is \" << argv[i] << std::endl;\n\n  return 0;\n}\n"}
{"id": 44692, "name": "Word wheel", "VB": "Const wheel=\"ndeokgelw\"\n\nSub print(s): \n  On Error Resume Next\n  WScript.stdout.WriteLine (s)  \n  If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub \n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n  x=LCase(ff.ReadLine) \n  If Len(x)>=3 Then \n    If  Not odic.exists(x) Then oDic.Add x,0\n  End If  \nWend  \nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\" \nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n  If  re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n  If  Not re.test(w) Then oDic.remove(w) \nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n  x=Mid(wheel,i,1)\n  If nDic.Exists(x) Then\n    a=nDic(x)\n    nDic(x)=Array(a(0)+1,0)\n  Else\n    nDic.add x,Array(1,0)\n  End If  \nNext\n\nFor Each w In oDic.Keys\n  For Each c In nDic.Keys\n    ndic(c)=Array(nDic(c)(0),0)\n  Next\n  For ii = 1 To len(w)\n    c=Mid(w,ii,1) \n    a=nDic(c)\n    If (a(0)=a(1)) Then  \n      oDic.Remove(w):Exit For\n    End If\n    nDic(c)=Array(a(0),a(1)+1)\n  Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys \n  print w  \nNext\n", "C++": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n\n\nclass letterset {\npublic:\n    letterset() {\n        count_.fill(0);\n    }\n    explicit letterset(const std::string& str) {\n        count_.fill(0);\n        for (char c : str)\n            add(c);\n    }\n    bool contains(const letterset& set) const {\n        for (size_t i = 0; i < count_.size(); ++i) {\n            if (set.count_[i] > count_[i])\n                return false;\n        }\n        return true;\n    }\n    unsigned int count(char c) const {\n        return count_[index(c)];\n    }\n    bool is_valid() const {\n        return count_[0] == 0;\n    }\n    void add(char c) {\n        ++count_[index(c)];\n    }\nprivate:\n    static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n    static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n    \n    \n    \n    std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n    std::string result;\n    if (begin != end) {\n        result += *begin++;\n        for (; begin != end; ++begin) {\n            result += sep;\n            result += *begin;\n        }\n    }\n    return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n                           int max_length) {\n    std::ifstream in(filename);\n    if (!in)\n        throw std::runtime_error(\"Cannot open file \" + filename);\n    std::string word;\n    dictionary result;\n    while (getline(in, word)) {\n        if (word.size() < min_length)\n            continue;\n        if (word.size() > max_length)\n            continue;\n        letterset set(word);\n        if (set.is_valid())\n            result.emplace_back(word, set);\n    }\n    return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n                char central_letter)  {\n    letterset set(letters);\n    if (central_letter == 0 && !letters.empty())\n        central_letter = letters.at(letters.size()/2);\n    std::map<size_t, std::vector<std::string>> words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        const auto& subset = pair.second;\n        if (subset.count(central_letter) > 0 && set.contains(subset))\n            words[word.size()].push_back(word);\n    }\n    size_t total = 0;\n    for (const auto& p : words) {\n        const auto& v = p.second;\n        auto n = v.size();\n        total += n;\n        std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n            << \" of length \" << p.first << \": \"\n            << join(v.begin(), v.end(), \", \") << '\\n';\n    }\n    std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n    size_t max_count = 0;\n    std::vector<std::pair<std::string, char>> max_words;\n    for (const auto& pair : dict) {\n        const auto& word = pair.first;\n        if (word.size() != word_length)\n            continue;\n        const auto& set = pair.second;\n        dictionary subsets;\n        for (const auto& p : dict) {\n            if (set.contains(p.second))\n                subsets.push_back(p);\n        }\n        letterset done;\n        for (size_t index = 0; index < word_length; ++index) {\n            char central_letter = word[index];\n            if (done.count(central_letter) > 0)\n                continue;\n            done.add(central_letter);\n            size_t count = 0;\n            for (const auto& p : subsets) {\n                const auto& subset = p.second;\n                if (subset.count(central_letter) > 0)\n                    ++count;\n            }\n            if (count > max_count) {\n                max_words.clear();\n                max_count = count;\n            }\n            if (count == max_count)\n                max_words.emplace_back(word, central_letter);\n        }\n    }\n    std::cout << \"Maximum word count: \" << max_count << '\\n';\n    std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n    for (const auto& pair : max_words)\n        std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n    const int word_length = 9;\n    int min_length = 3;\n    std::string letters = \"ndeokgelw\";\n    std::string filename = \"unixdict.txt\";\n    char central_letter = 0;\n    bool do_part2 = false;\n    \n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (option_filename, po::value<std::string>(), \"name of dictionary file\")\n        (option_wheel, po::value<std::string>(), \"word wheel letters\")\n        (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n        (option_min_length, po::value<int>(), \"minimum word length\")\n        (option_part2, \"include part 2\");\n\n    try {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(option_filename))\n            filename = vm[option_filename].as<std::string>();\n        if (vm.count(option_wheel))\n            letters = vm[option_wheel].as<std::string>();\n        if (vm.count(option_central))\n            central_letter = vm[option_central].as<char>();\n        if (vm.count(option_min_length))\n            min_length = vm[option_min_length].as<int>();\n        if (vm.count(option_part2))\n            do_part2 = true;\n\n        auto dict = load_dictionary(filename, min_length, word_length);\n        \n        word_wheel(dict, letters, central_letter);\n        \n        if (do_part2) {\n            std::cout << '\\n';\n            find_max_word_count(dict, word_length);\n        }\n    } catch (const std::exception& ex) {\n        std::cerr << ex.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n"}
{"id": 44693, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "C++": "#include <vector>\n#include <iostream>\n\nint main()\n{\n  std::vector<int> a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"}
{"id": 44694, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 44695, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n     \n     \n     long int integer_input;\n     string string_input;\n     cout << \"Enter an integer:  \";\n     cin >> integer_input;\n     cout << \"Enter a string:  \";\n     cin >> string_input;\n     return 0;\n}\n"}
{"id": 44696, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 44697, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "C++": "#include <iostream>\n#include <windows.h>\n#include <mmsystem.h>\n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n    unsigned long word; \n    unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n    midi()\n    {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t    std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t    device = 0;\n\t}\n    }\n    ~midi()\n    {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n    }\n    bool isOpen() { return device != 0; }\n    void setInstrument( byte i )\n    {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void playNote( byte n, unsigned i )\n    {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n    }\n\nprivate:\n    void playNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    void stopNote( byte n )\n    {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n    }\n    HMIDIOUT device;\n    midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n    midi m;\n    if( m.isOpen() )\n    {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t    m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n    }\n    return 0;\n}\n"}
{"id": 44698, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 44699, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "C++": "#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <set>\n\nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , \n      std::set<int> & , const int  ) ;\n\nint main( ) {\n   std::vector<boost::tuple<std::string , int , int> > items ;\n   \n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set<int> bestItems ; \n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \" !\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set<int>::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \" !\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {\n   \n   \n   \n   \n   \n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set<int> solutionSets[ n ][ weightlimit ] ;\n   std::set<int> emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n"}
{"id": 44700, "name": "Primes - allocate descendants to their ancestors", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\ntypedef unsigned long long integer;\n\n\nstd::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {\n    std::vector<integer> result;\n    for (integer a = ancestor[n]; a != 0 && a != n; ) {\n        n = a;\n        a = ancestor[n];\n        result.push_back(n);\n    }\n    return result;\n}\n\nvoid print_vector(const std::vector<integer>& vec) {\n    if (vec.empty()) {\n        std::cout << \"none\\n\";\n        return;\n    }\n    auto i = vec.begin();\n    std::cout << *i++;\n    for (; i != vec.end(); ++i)\n        std::cout << \", \" << *i;\n    std::cout << '\\n';\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    for (integer p = 3; p * p <= n; p += 2) {\n        if (n % p == 0)\n            return false;\n    }\n    return true;\n}\n\nint main(int argc, char** argv) {\n    const size_t limit = 100;\n\n    std::vector<integer> ancestor(limit, 0);\n    std::vector<std::vector<integer>> descendants(limit);\n\n    for (size_t prime = 0; prime < limit; ++prime) {\n        if (!is_prime(prime))\n            continue;\n        descendants[prime].push_back(prime);\n        for (size_t i = 0; i + prime < limit; ++i) {\n            integer s = i + prime;\n            for (integer n : descendants[i]) {\n                integer prod = n * prime;\n                descendants[s].push_back(prod);\n                if (prod < limit)\n                    ancestor[prod] = s;\n            }\n        }\n    }\n\n    \n    size_t total_descendants = 0;\n    for (integer i = 1; i < limit; ++i) {\n        std::vector<integer> ancestors(get_ancestors(ancestor, i));\n        std::cout << \"[\" << i << \"] Level: \" << ancestors.size() << '\\n';\n        std::cout << \"Ancestors: \";\n        std::sort(ancestors.begin(), ancestors.end());\n        print_vector(ancestors);\n        \n        std::cout << \"Descendants: \";\n        std::vector<integer>& desc = descendants[i];\n        if (!desc.empty()) {\n            std::sort(desc.begin(), desc.end());\n            if (desc[0] == i)\n                desc.erase(desc.begin());\n        }\n        std::cout << desc.size() << '\\n';\n        total_descendants += desc.size();\n        if (!desc.empty())\n            print_vector(desc);\n        std::cout << '\\n';\n    }\n    std::cout << \"Total descendants: \" << total_descendants << '\\n';\n    return 0;\n}\n"}
{"id": 44701, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 44702, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "C++": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid print(const std::vector<std::vector<int>>& v) {\n  std::cout << \"{ \";\n  for (const auto& p : v) {\n    std::cout << \"(\";\n    for (const auto& e : p) {\n      std::cout << e << \" \";\n    }\n    std::cout << \") \";\n  }\n  std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector<std::vector<int>>& lists) {\n  std::vector<std::vector<int>> result;\n  if (std::find_if(std::begin(lists), std::end(lists), \n    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n    return result;\n  }\n  for (auto& e : lists[0]) {\n    result.push_back({ e });\n  }\n  for (size_t i = 1; i < lists.size(); ++i) {\n    std::vector<std::vector<int>> temp;\n    for (auto& e : result) {\n      for (auto f : lists[i]) {\n        auto e_tmp = e;\n        e_tmp.push_back(f);\n        temp.push_back(e_tmp);\n      }\n    }\n    result = temp;\n  }\n  return result;\n}\n\nint main() {\n  std::vector<std::vector<int>> prods[] = {\n    { { 1, 2 }, { 3, 4 } },\n    { { 3, 4 }, { 1, 2} },\n    { { 1, 2 }, { } },\n    { { }, { 1, 2 } },\n    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n    { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n    { { 1, 2, 3 }, { }, { 500, 100 } }\n  };\n  for (const auto& p : prods) {\n    print(product(p));\n  }\n  std::cin.ignore();\n  std::cin.get();\n  return 0;\n}\n"}
{"id": 44703, "name": "Proper divisors", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n", "C++": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> properDivisors ( int number ) {\n   std::vector<int> divisors ;\n   for ( int i = 1 ; i < number / 2 + 1 ; i++ )\n      if ( number % i == 0 )\n\t divisors.push_back( i ) ;\n   return divisors ;\n}\n\nint main( ) {\n   std::vector<int> divisors ;\n   unsigned int maxdivisors = 0 ;\n   int corresponding_number = 0 ;\n   for ( int i = 1 ; i < 11 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      std::cout << \"Proper divisors of \" << i << \":\\n\" ;\n      for ( int number : divisors ) { \n\t std::cout << number << \" \" ;\n      }\n      std::cout << std::endl ;\n      divisors.clear( ) ;\n   }\n   for ( int i = 11 ; i < 20001 ; i++ ) {\n      divisors =  properDivisors ( i ) ;\n      if ( divisors.size( ) > maxdivisors ) {\n\t maxdivisors = divisors.size( ) ;\n\t corresponding_number = i ;\n      }\n      divisors.clear( ) ;\n   }\n\n   std::cout << \"Most divisors has \" << corresponding_number <<\n      \" , it has \" << maxdivisors << \" divisors!\\n\" ; \n   return 0 ;\n}\n"}
{"id": 44704, "name": "XML_Output", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n", "C++": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n   std::vector<std::string> names , remarks ;\n   names.push_back( \"April\" ) ;\n   names.push_back( \"Tam O'Shantor\" ) ;\n   names.push_back ( \"Emily\" ) ;\n   remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n   remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n   remarks.push_back( \"Short & shrift\" ) ;\n   std::cout << \"This is in XML:\\n\" ;\n   std::cout << create_xml( names , remarks ) << std::endl ;\n   return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n      std::vector<std::string> & remarks ) {\n   std::vector<std::pair<std::string , std::string> > entities ;\n   entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n   entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n   entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n   std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n   std::vector<std::string>::iterator vsi = names.begin( ) ;\n   typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n   for ( ; vsi != names.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n      for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n      }\n   }\n   for ( int i = 0 ; i < names.size( ) ; i++ ) {\n      xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n   }\n   xmlstring.append( \"</CharacterRemarks>\" ) ;\n   return xmlstring ;\n}\n"}
{"id": 44705, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 44706, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "C++": "#include <windows.h>\n#include <string>\n#include <vector>\n\n\nusing namespace std;\n\n\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n\nclass vector2\n{\npublic:\n    vector2() { x = y = 0; }\n    vector2( float a, float b )  { x = a; y = b; }\n    void set( float a, float b ) { x = a; y = b; }\n    float x, y;\n};\n\nclass myBitmap\n{\npublic:\n    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n    ~myBitmap()\n    {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n    }\n\n    bool create( int w, int h )\n    {\n\tBITMAPINFO    bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize        = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes      = 1;\n\tbi.bmiHeader.biWidth       =  w;\n\tbi.bmiHeader.biHeight      = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n    }\n\n    void clear( BYTE clr = 0 )\n    {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n    }\n\n    void setBrushColor( DWORD bClr )\n    {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n    }\n\n    void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n    void setPenWidth( int w )   { wid = w; createPen(); }\n\n    void saveBitmap( string path )\n    {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO       infoheader;\n\tBITMAP           bitmap;\n\tDWORD            wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType    = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n    }\n\n    HDC getDC() const     { return hdc; }\n    int getWidth() const  { return width; }\n    int getHeight() const { return height; }\n\nprivate:\n    void createPen()\n    {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n    }\n\n    HBITMAP bmp;\n    HDC     hdc;\n    HPEN    pen;\n    HBRUSH  brush;\n    void    *pBits;\n    int     width, height, wid;\n    DWORD   clr;\n};\n\nclass plot\n{\npublic:\n    plot() { bmp.create( 512, 512 ); }\n\n    void draw( vector<vector2>* pairs )\n    {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t\n    }\n\nprivate:\n    void drawGraph( vector<vector2>* pairs )\n    {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t    wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t    SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t    wsprintf( txt, \"%d\", x );\n\t    SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t    c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n    }\n\n    void plotIt( vector<vector2>* pairs )\n    {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector<vector2>::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t    a = MWID + HSTEP * static_cast<int>( ( *it ).x );\n\t    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );\n\t    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t    FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n    }\n\n    myBitmap bmp;\n};\n\nint main( int argc, char* argv[] )\n{\n    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n    plot pt;\n    vector<vector2> pairs;\n    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n    pt.draw( &pairs );\n    system( \"pause\" );\n\n    return 0;\n}\n\n"}
{"id": 44707, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "C++": "#include <iostream>\n#include <string>\n#include <iterator>\n#include <regex>\n\nint main()\n{\n  std::regex re(\".* string$\");\n  std::string s = \"Hi, I am a string\";\n\n  \n  if (std::regex_match(s, re))\n    std::cout << \"The string matches.\\n\";\n  else\n    std::cout << \"Oops - not found?\\n\";\n\n  \n  std::regex re2(\" a.*a\");\n  std::smatch match;\n  if (std::regex_search(s, match, re2))\n  {\n    std::cout << \"Matched \" << match.length()\n              << \" characters starting at \" << match.position() << \".\\n\";\n    std::cout << \"Matched character sequence: \\\"\"\n              << match.str() << \"\\\"\\n\";\n  }\n  else\n  {\n    std::cout << \"Oops - not found?\\n\";\n  }\n\n  \n  std::string dest_string;\n  std::regex_replace(std::back_inserter(dest_string),\n                       s.begin(), s.end(),\n                       re2,\n                       \"'m now a changed\");\n  std::cout << dest_string << std::endl;\n}\n"}
{"id": 44708, "name": "Hash from two arrays", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n", "C++": "#include <unordered_map>\n#include <string>\n\nint main()\n{\n  std::string keys[] = { \"1\", \"2\", \"3\" };\n  std::string vals[] = { \"a\", \"b\", \"c\" };\n \n  std::unordered_map<std::string, std::string> hash;\n  for( int i = 0 ; i < 3 ; i++ )\n     hash[ keys[i] ] = vals[i] ;\n}\n"}
{"id": 44709, "name": "Colour pinstripe_Display", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n"}
{"id": 44710, "name": "Colour pinstripe_Display", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n", "C++": "#include <windows.h>\n\n\nclass pinstripe\n{\npublic:\n    pinstripe()                        { createColors(); }\n    void setDimensions( int x, int y ) { _mw = x; _mh = y; }\n    void createColors()\n    {\n\tcolors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );\n\tcolors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); \n\tcolors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); \n\tcolors[7] = RGB( 255, 255, 255 );\n    }\n\n    void draw( HDC dc )\n    {\n        HPEN pen;\n\tint lh = _mh / 4, row, cp;\n\tfor( int lw = 1; lw < 5; lw++ )\n\t{\n\t    cp = 0;\n            row = ( lw - 1 ) * lh;\n\t    for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )\n\t    {\n\t\tpen = CreatePen( PS_SOLID, lw, colors[cp] );\n\t        ++cp %= 8;\n\n\t\tSelectObject( dc, pen );\n\t\tMoveToEx( dc, x, row, NULL );\n\t\tLineTo( dc, x, row + lh );\n\t\tDeleteObject( pen );\n\t    }\n\t}\n    }\n\nprivate:\n    int _mw, _mh;\n    DWORD colors[8];\n};\n\npinstripe pin;\n\n\nvoid PaintWnd( HWND hWnd )\n{\n    PAINTSTRUCT ps;\n    HDC hdc = BeginPaint( hWnd, &ps );\n    pin.draw( hdc );\n    EndPaint( hWnd, &ps );\n}\n\nLRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n{\n    switch( msg )\n    {\n\tcase WM_DESTROY: PostQuitMessage( 0 ); break;\n\tcase WM_PAINT: PaintWnd( hWnd ); break;\n\tdefault:\n\t    return DefWindowProc( hWnd, msg, wParam, lParam );\n    }\n    return 0;\n}\n\nHWND InitAll( HINSTANCE hInstance )\n{\n    WNDCLASSEX wcex;\n    ZeroMemory( &wcex, sizeof( wcex ) );\n\n    wcex.cbSize\t       = sizeof( WNDCLASSEX );\n    wcex.style\t       = CS_HREDRAW | CS_VREDRAW;\n    wcex.lpfnWndProc   = WndProc;\n    wcex.hInstance     = hInstance;\n    wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );\n    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n    wcex.lpszClassName = \"_CLR_PS_\";\n\n    RegisterClassEx( &wcex ); \n    return CreateWindow( \"_CLR_PS_\", \".: Clr Pinstripe -- PJorente :.\", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );\n}\n\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n    srand( GetTickCount() );\n\n    HWND hwnd = InitAll( hInstance );\n    if( !hwnd ) return -1;\n\n    int mw = GetSystemMetrics( SM_CXSCREEN ),\n\tmh = GetSystemMetrics( SM_CYSCREEN );\n\n    pin.setDimensions( mw, mh );\n\n    RECT rc = { 0, 0, mw, mh };\n\n    AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );\n    int w = rc.right  - rc.left, \n\th = rc.bottom - rc.top;\n\n    int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),\n\tposY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );\n\n    SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );\n    ShowWindow( hwnd, nCmdShow );\n    UpdateWindow( hwnd );\n\n    MSG msg;\n    ZeroMemory( &msg, sizeof( msg ) );\n    while( msg.message != WM_QUIT )\n    {\n\tif( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t{\n\t    TranslateMessage( &msg );\n\t    DispatchMessage( &msg );\n\t}\n    }\n    return UnregisterClass( \"_CLR_PS_\", hInstance );\n}\n\n"}
{"id": 44711, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n", "C++": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n\ntemplate <typename iterator>\nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    for (--end; begin < end; ) {\n        iterator new_begin = end;\n        iterator new_end = begin;\n        for (iterator i = begin; i < end; ++i) {\n            iterator j = i + 1;\n            if (*j < *i) {\n                std::iter_swap(i, j);\n                new_end = i;\n            }\n        }\n        end = new_end;\n        for (iterator i = end; i > begin; --i) {\n            iterator j = i - 1;\n            if (*i < *j) {\n                std::iter_swap(i, j);\n                new_begin = i;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\ntemplate <typename iterator>\nvoid print(iterator begin, iterator end) {\n    if (begin == end)\n        return;\n    std::cout << *begin++;\n    while (begin != end)\n        std::cout << ' ' << *begin++;\n    std::cout << '\\n';\n}\n\nint main() {\n    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n    std::cout << \"before: \";\n    print(v.begin(), v.end());\n    cocktail_shaker_sort(v.begin(), v.end());\n    assert(std::is_sorted(v.begin(), v.end()));\n    std::cout << \"after: \";\n    print(v.begin(), v.end());\n    return 0;\n}\n"}
{"id": 44712, "name": "Animate a pendulum", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n", "C++": "#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\n\n\n\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include <wx/wx.h>\n#include <wx/dialog.h>\n#else\n#include <wx/wxprec.h>\n#endif\n#include <wx/timer.h>\n#include <wx/dcbuffer.h>\n#include <cmath>\n\nclass wxPendulumDlgApp : public wxApp\n{\n    public:\n        bool OnInit();\n        int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n    public:\n\n        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n        virtual ~wxPendulumDlg();\n\t\n\t\t\n        void wxPendulumDlgPaint(wxPaintEvent& event);\n        void wxPendulumDlgSize(wxSizeEvent& event);\n        void OnTimer(wxTimerEvent& event);\n\n    private:\n\n\t\t\n        wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble  \t m_Angle;\n\t\tdouble       m_AngleVelocity;\n\n        enum wxIDs\n        {\n            ID_WXTIMER1 = 1001,\n            ID_DUMMY_VALUE_ \n        };\n\n        void OnClose(wxCloseEvent& event);\n        void CreateGUIControls();\n\n        DECLARE_EVENT_TABLE()\n};\n\n#endif \n"}
{"id": 44713, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 44714, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "C++": "#include <bitset>\n#include <iostream>\n#include <string>\n#include <assert.h>\n\nuint32_t gray_encode(uint32_t b)\n{\n    return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n    {\n        if (g & bit) g ^= bit >> 1;\n    }\n    return g;\n}\n\nstd::string to_binary(int value) \n{\n    const std::bitset<32> bs(value);\n    const std::string str(bs.to_string());\n    const size_t pos(str.find('1'));\n    return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n    std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n    for (uint32_t n = 0; n < 32; ++n)\n    {\n        uint32_t g = gray_encode(n);\n        assert(gray_decode(g) == n);\n\n        std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n    }\n}\n"}
{"id": 44715, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 44716, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "C++": "#include <deque>\n#include <algorithm>\n#include <ostream>\n#include <iterator>\n\nnamespace cards\n{\nclass card\n{\npublic:\n    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,\n                    jack, queen, king, ace, pip_count };\n    enum suite_type { hearts, spades, diamonds, clubs, suite_count };\n    enum { unique_count = pip_count * suite_count };\n\n    card(suite_type s, pip_type p): value(s + suite_count * p) {}\n\n    explicit card(unsigned char v = 0): value(v) {}\n\n    pip_type pip() { return pip_type(value / suite_count); }\n\n    suite_type suite() { return suite_type(value % suite_count); }\n\nprivate:\n    unsigned char value;\n};\n\nconst char* const pip_names[] =\n    { \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n      \"jack\", \"queen\", \"king\", \"ace\" };\n\nstd::ostream& operator<<(std::ostream& os, card::pip_type pip)\n{\n    return os << pip_names[pip];\n}\n\nconst char* const suite_names[] =\n    { \"hearts\", \"spades\", \"diamonds\", \"clubs\" };\n\nstd::ostream& operator<<(std::ostream& os, card::suite_type suite)\n{\n    return os << suite_names[suite];\n}\n\nstd::ostream& operator<<(std::ostream& os, card c)\n{\n    return os << c.pip() << \" of \" << c.suite();\n}\n\nclass deck\n{\npublic:\n    deck()\n    {\n        for (int i = 0; i < card::unique_count; ++i) {\n            cards.push_back(card(i));\n        }\n    }\n\n    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }\n\n    card deal() { card c = cards.front(); cards.pop_front(); return c; }\n\n    typedef std::deque<card>::const_iterator const_iterator;\n    const_iterator begin() const { return cards.cbegin(); }\n    const_iterator end() const { return cards.cend(); }\nprivate:\n    std::deque<card> cards;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const deck& d)\n{\n    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, \"\\n\"));\n    return os;\n}\n}\n"}
{"id": 44717, "name": "Arrays", "VB": "Option Base {0|1}\n", "C++": "#include <array>\n#include <vector>\n\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n\ntemplate <typename Array>\nvoid demonstrate(Array& array)\n{\n  \n  array[2] = \"Three\";  \n                       \n  array.at(1) = \"Two\"; \n                       \n  \n  \n  std::reverse(begin(array), end(array));\n  std::for_each(begin(array), end(array),\n    [](typename Array::value_type const& element) \n    {\n      std::cout << element << ' ';\n    });\n  \n  std::cout << '\\n';\n}\n\nint main()\n{\n  \n  auto fixed_size_array = std::array<std::string, 3>{ \"One\", \"Four\", \"Eight\" };\n  \n  \n  \n  auto dynamic_array = std::vector<std::string>{ \"One\", \"Four\" };\n  dynamic_array.push_back(\"Eight\"); \n  \n  \n  demonstrate(fixed_size_array);\n  demonstrate(dynamic_array);\n}\n"}
{"id": 44718, "name": "Sierpinski carpet", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "C++": "\n\n\n#include <cstdint>\n#include <cstdlib>\n#include <cstdio>\n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n    --v;            \n    return v ^ (v & (v>>1) & bct_low_bits);     \n}\n\nint main (int argc, char *argv[])\n{\n    \n    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n    \n    if (n < 0 || 9 < n) {                       \n        std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n        return 1;\n    }\n\n    const int32_t size_bct = 1<<(n*2);          \n    \n    int32_t y = size_bct;\n    do {                                        \n        y = bct_decrement(y);                   \n        int32_t x = size_bct;\n        do {                                    \n            x = bct_decrement(x);               \n            \n            std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n        } while (0 < x);\n        std::putchar('\\n');\n    } while (0 < y);\n\n    return 0;\n}\n"}
{"id": 44719, "name": "Sorting algorithms_Bogosort", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n\ntemplate <typename RandomAccessIterator, typename Predicate>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n               Predicate p) {\n  std::random_device rd;\n  std::mt19937 generator(rd());\n  while (!std::is_sorted(begin, end, p)) {\n    std::shuffle(begin, end, generator);\n  }\n}\n\ntemplate <typename RandomAccessIterator>\nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n  bogo_sort(\n      begin, end,\n      std::less<\n          typename std::iterator_traits<RandomAccessIterator>::value_type>());\n}\n\nint main() {\n  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n  bogo_sort(std::begin(a), std::end(a));\n  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, \" \"));\n  std::cout << \"\\n\";\n}\n"}
{"id": 44720, "name": "Euler method", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n", "C++": "#include <iomanip>\n#include <iostream>\n\ntypedef double F(double,double);\n\n\nvoid euler(F f, double y0, double a, double b, double h)\n{\n    double y = y0;\n    for (double t = a; t < b; t += h)\n    {\n        std::cout << std::fixed << std::setprecision(3) << t << \" \" << y << \"\\n\";\n        y += h * f(t, y);\n    }\n    std::cout << \"done\\n\";\n}\n\n\ndouble newtonCoolingLaw(double, double t)\n{\n    return -0.07 * (t - 20);\n}\n\nint main()\n{\n    euler(newtonCoolingLaw, 100, 0, 100,  2);\n    euler(newtonCoolingLaw, 100, 0, 100,  5);\n    euler(newtonCoolingLaw, 100, 0, 100, 10);\n}\n"}
{"id": 44721, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "C++": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;   \n   \n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;  \n   \n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;     \n   std::cout << '\\n' ;\n   \n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n"}
{"id": 44722, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "C++": "#include <iostream>\n#include <string>\n\nint main()\n{\n  std::string s = \"0123456789\";\n\n  int const n = 3;\n  int const m = 4;\n  char const c = '2';\n  std::string const sub = \"456\";\n\n  std::cout << s.substr(n, m)<< \"\\n\";\n  std::cout << s.substr(n) << \"\\n\";\n  std::cout << s.substr(0, s.size()-1) << \"\\n\";\n  std::cout << s.substr(s.find(c), m) << \"\\n\";\n  std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n"}
{"id": 44723, "name": "JortSort", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n", "C++": "#include <algorithm>\n#include <string>\n#include <iostream>\n#include <iterator> \n\nclass jortSort {\npublic:\n    template<class T>\n    bool jort_sort( T* o, size_t s ) {\n        T* n = copy_array( o, s );\n        sort_array( n, s );\n        bool r = false;\n\n        if( n ) {\n            r = check( o, n, s );\n            delete [] n;\n        }\n        return r;\n    }\n\nprivate:\n    template<class T>\n    T* copy_array( T* o, size_t s ) {\n        T* z = new T[s];\n        memcpy( z, o, s * sizeof( T ) );\n        \n        return z;\n    }\n    template<class T>\n    void sort_array( T* n, size_t s ) {\n        std::sort( n, n + s );\n    }\n    template<class T>\n    bool check( T* n, T* o, size_t s ) {\n        for( size_t x = 0; x < s; x++ )\n            if( n[x] != o[x] ) return false;\n        return true;\n    }\n};\n\njortSort js;\n\ntemplate<class T>\nvoid displayTest( T* o, size_t s ) {\n    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, \" \" ) );\n    std::cout << \": -> The array is \" << ( js.jort_sort( o, s ) ? \"sorted!\" : \"not sorted!\" ) << \"\\n\\n\";\n}\n\nint main( int argc, char* argv[] ) {\n    const size_t s = 5;\n    std::string oStr[] = { \"5\", \"A\", \"D\", \"R\", \"S\" };\n    displayTest( oStr, s );\n    std::swap( oStr[0], oStr[1] );\n    displayTest( oStr, s );\n\n    int oInt[] = { 1, 2, 3, 4, 5 };\n    displayTest( oInt, s );\n    std::swap( oInt[0], oInt[1] );\n    displayTest( oInt, s );\n\n    return 0;\n}\n"}
{"id": 44724, "name": "Leap year", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n", "C++": "#include <iostream>\n\nbool is_leap_year(int year) {\n  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n  for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n    std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n  }\n}\n"}
{"id": 44725, "name": "Combinations and permutations", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n", "C++": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n\nusing namespace boost::multiprecision;\n\nmpz_int p(uint n, uint p) {\n    mpz_int r = 1;\n    mpz_int k = n - p;\n    while (n > k)\n        r *= n--;\n    return r;\n}\n\nmpz_int c(uint n, uint k) {\n    mpz_int r = p(n, k);\n    while (k)\n        r /= k--;\n    return r;\n}\n\nint main() {\n    for (uint i = 1u; i < 12u; i++)\n        std::cout << \"P(12,\" << i << \") = \" << p(12u, i) << std::endl;\n    for (uint i = 10u; i < 60u; i += 10u)\n        std::cout << \"C(60,\" << i << \") = \" << c(60u, i) << std::endl;\n\n    return 0;\n}\n"}
{"id": 44726, "name": "Sort numbers lexicographically", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <vector>\n\nvoid lexicographical_sort(std::vector<int>& numbers) {\n    std::vector<std::string> strings(numbers.size());\n    std::transform(numbers.begin(), numbers.end(), strings.begin(),\n                   [](int i) { return std::to_string(i); });\n    std::sort(strings.begin(), strings.end());\n    std::transform(strings.begin(), strings.end(), numbers.begin(),\n                   [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector<int> lexicographically_sorted_vector(int n) {\n    std::vector<int> numbers(n >= 1 ? n : 2 - n);\n    std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n    lexicographical_sort(numbers);\n    return numbers;\n}\n\ntemplate <typename T>\nvoid print_vector(std::ostream& out, const std::vector<T>& v) {\n    out << '[';\n    if (!v.empty()) {\n        auto i = v.begin();\n        out << *i++;\n        for (; i != v.end(); ++i)\n            out << ',' << *i;\n    }\n    out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n    for (int i : { 0, 5, 13, 21, -22 }) {\n        std::cout << i << \": \";\n        print_vector(std::cout, lexicographically_sorted_vector(i));\n    }\n    return 0;\n}\n"}
{"id": 44727, "name": "Number names", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n", "C++": "#include <string>\n#include <iostream>\nusing std::string;\n\nconst char* smallNumbers[] = {\n  \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n  \"six\", \"seven\", \"eight\", \"nine\", \"ten\",\n  \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n  \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n \nstring spellHundreds(unsigned n) {\n  string res;\n  if (n > 99) {\n    res = smallNumbers[n/100];\n    res += \" hundred\";\n    n %= 100;\n    if (n) res += \" and \";\n  }\n  if (n >= 20) {\n    static const char* Decades[] = {\n      \"\", \"\", \"twenty\", \"thirty\", \"forty\",\n      \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n    };\n    res += Decades[n/10];\n    n %= 10;\n    if (n) res += \"-\";\n  }\n  if (n < 20 && n > 0)\n    res += smallNumbers[n];\n  return res;\n}\n\n\nconst char* thousandPowers[] = {\n  \" billion\", \" million\",  \" thousand\", \"\" };\n\ntypedef unsigned long Spellable;\n\nstring spell(Spellable n) {\n  if (n < 20) return smallNumbers[n];\n  string res;\n  const char** pScaleName = thousandPowers;\n  Spellable scaleFactor = 1000000000;\t\n  while (scaleFactor > 0) {\n    if (n >= scaleFactor) {\n      Spellable h = n / scaleFactor;\n      res += spellHundreds(h) + *pScaleName;\n      n %= scaleFactor;\n      if (n) res += \", \";\n    }\n    scaleFactor /= 1000;\n    ++pScaleName;\n  }\n  return res;\n}\n\nint main() {\n#define SPELL_IT(x) std::cout << #x \" \" << spell(x) << std::endl;\n  SPELL_IT(      99);\n  SPELL_IT(     300);\n  SPELL_IT(     310);\n  SPELL_IT(    1501);\n  SPELL_IT(   12609);\n  SPELL_IT(  512609);\n  SPELL_IT(43112609);\n  SPELL_IT(1234567890);\n  return 0;\n}\n"}
{"id": 44728, "name": "Sorting algorithms_Shell sort", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n", "C++": "#include <time.h>\n#include <iostream>\n\n\nusing namespace std;\n\n\nconst int MAX = 126;\nclass shell\n{\npublic:\n    shell() \n    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n    void sort( int* a, int count )\n    {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t    if( count > _gap[x] )\n\t    { _idx = x; break; }\n\n\tsortIt( a );\n    }\n\nprivate:\t\n    void sortIt( int* arr )\n    {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t    sorted = true;\n\t    int st = 0;\n\t    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t    {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t    }\n\t    if( ++_idx >= 8 ) _idx = 8;\n\t    if( sorted && _idx == 8 ) break;\n\t}\n    }\n\n    void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n    int _gap[9], _idx, _cnt;\n};\n\nint main( int argc, char* argv[] )\n{\n    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];\n    for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n    cout << \" Before: \\n=========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl; shell s; s.sort( arr, MAX );\n\t\n    cout << \" After: \\n========\\n\";\n    for( int x = 0; x < 7; x++ )\n    {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n    }\n    cout << endl << endl; return system( \"pause\" );\n}\n\n"}
{"id": 44729, "name": "Doubly-linked list_Definition", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n", "C++": "#include <iostream>\n#include <list>\n\nint main ()\n{\n    std::list<int> numbers {1, 5, 7, 0, 3, 2};\n    numbers.insert(numbers.begin(), 9); \n    numbers.insert(numbers.end(), 4); \n    auto it = std::next(numbers.begin(), numbers.size() / 2); \n    numbers.insert(it, 6); \n    for(const auto& i: numbers)\n        std::cout << i << ' ';\n    std::cout << '\\n';\n}\n"}
{"id": 44730, "name": "Letter frequency", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n", "C++": "#include <fstream>\n#include <iostream>\n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \n\t\t; \n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n"}
{"id": 44731, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "C++": "\n#include <cstdlib>\n#include <string>\n#include <sstream>\n\n\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\n\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n"}
{"id": 44732, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 44733, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "C++": "#include <algorithm>\n#include <iostream>\n#include <string>\n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n    str.erase(\n        std::remove_if(str.begin(), str.end(), [&](char c){\n            return chars.find(c) != std::string::npos;\n        }),\n        str.end()\n    );\n    return str;\n}\n\nint main()\n{\n    std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n    return 0;\n}\n"}
{"id": 44734, "name": "Averages_Arithmetic mean", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n", "C++": "#include <vector>\n\ndouble mean(const std::vector<double>& numbers)\n{\n     if (numbers.size() == 0)\n          return 0;\n\n     double sum = 0;\n     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)\n          sum += *i;\n     return sum / numbers.size();\n}\n"}
{"id": 44735, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 44736, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "C++": "#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\nclass command {\npublic:\n    command(const std::string&, size_t);\n    const std::string& cmd() const { return cmd_; }\n    size_t min_length() const { return min_len_; }\n    bool match(const std::string&) const;\nprivate:\n    std::string cmd_;\n    size_t min_len_;\n};\n\n\ncommand::command(const std::string& cmd, size_t min_len)\n    : cmd_(cmd), min_len_(min_len) {}\n\n\nbool command::match(const std::string& str) const {\n    size_t olen = str.length();\n    return olen >= min_len_ && olen <= cmd_.length()\n        && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n    try {\n        size_t pos;\n        int i = std::stoi(word, &pos, 10);\n        if (pos < word.length())\n            return false;\n        value = i;\n        return true;\n    } catch (const std::exception& ex) {\n        return false;\n    }\n}\n\n\nvoid uppercase(std::string& str) {\n    std::transform(str.begin(), str.end(), str.begin(),\n        [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n    explicit command_list(const char*);\n    const command* find_command(const std::string&) const;\nprivate:\n    std::vector<command> commands_;\n};\n\ncommand_list::command_list(const char* table) {\n    std::istringstream is(table);\n    std::string word;\n    std::vector<std::string> words;\n    while (is >> word) {\n        uppercase(word);\n        words.push_back(word);\n    }\n    for (size_t i = 0, n = words.size(); i < n; ++i) {\n        word = words[i];\n        \n        \n        \n        int len = word.length();\n        if (i + 1 < n && parse_integer(words[i + 1], len))\n            ++i;\n        commands_.push_back(command(word, len));\n    }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n    auto iter = std::find_if(commands_.begin(), commands_.end(),\n        [&word](const command& cmd) { return cmd.match(word); });\n    return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n    std::string output;\n    std::istringstream is(input);\n    std::string word;\n    while (is >> word) {\n        if (!output.empty())\n            output += ' ';\n        uppercase(word);\n        const command* cmd_ptr = commands.find_command(word);\n        if (cmd_ptr)\n            output += cmd_ptr->cmd();\n        else\n            output += \"*error*\";\n    }\n    return output;\n}\n\nint main() {\n    command_list commands(command_table);\n    std::string input(\"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\");\n    std::string output(test(commands, input));\n    std::cout << \" input: \" << input << '\\n';\n    std::cout << \"output: \" << output << '\\n';\n    return 0;\n}\n"}
{"id": 44737, "name": "Tokenize a string with escaping", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n", "C++": "#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> tokenize(const string& input, char seperator, char escape) {\n    vector<string> output;\n    string token;\n\n    bool inEsc = false;\n    for (char ch : input) {\n        if (inEsc) {\n            inEsc = false;\n        } else if (ch == escape) {\n            inEsc = true;\n            continue;\n        } else if (ch == seperator) {\n            output.push_back(token);\n            token = \"\";\n            continue;\n        }\n        token += ch;\n    }\n    if (inEsc)\n        throw new invalid_argument(\"Invalid terminal escape\");\n\n    output.push_back(token);\n    return output;\n}\n\nint main() {\n    string sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n\n    cout << sample << endl;\n    cout << '[';\n    for (auto t : tokenize(sample, '|', '^')) {\n        cout << '\"' << t << \"\\\", \";\n    }\n    cout << ']' << endl;\n\n    return 0;\n}\n"}
{"id": 44738, "name": "Hello world_Text", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n", "C++": "#include <iostream>\n\nint main () {\n  std::cout << \"Hello world!\" << std::endl;\n}\n"}
{"id": 44739, "name": "Forward difference", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n", "C++": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator forward_difference(InputIterator first, InputIterator last,\n                                   OutputIterator dest)\n{\n  \n  if (first == last)\n    return dest;\n\n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n\n  value_type temp = *first++;\n  while (first != last)\n  {\n    value_type temp2 = *first++;\n    *dest++ = temp2 - temp;\n    temp = temp2;\n  }\n\n  return dest;\n}\n\n\n\n\n\n\n\n\n\n\n\ntemplate<typename InputIterator, typename OutputIterator>\n OutputIterator nth_forward_difference(int order,\n                                       InputIterator first, InputIterator last,\n                                       OutputIterator dest)\n{\n  \n  if (order == 0)\n    return std::copy(first, last, dest);\n\n  \n  if (order == 1)\n    return forward_difference(first, last, dest);\n\n  \n  typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n  std::vector<value_type> temp_storage;\n\n  \n  forward_difference(first, last, std::back_inserter(temp_storage));\n\n  \n  typename std::vector<value_type>::iterator begin = temp_storage.begin(),\n                                             end = temp_storage.end();\n  for (int i = 1; i < order-1; ++i)\n    end = forward_difference(begin, end, begin);\n\n  \n  return forward_difference(begin, end, dest);\n}\n\n\n#include <iostream>\n\nint main()\n{\n  double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };\n\n  \n  std::vector<double> dest;\n  nth_forward_difference(1, array, array+10, std::back_inserter(dest));\n\n  \n  std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, \" \"));\n  std::cout << std::endl;\n\n  \n  \n  double* end = nth_forward_difference(3, array, array+10, array);\n\n  for (double* p = array; p < end; ++p)\n    std::cout << *p << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n"}
{"id": 44740, "name": "Primality by trial division", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n", "C++": "#include <cmath>\n\nbool is_prime(unsigned int n)\n{\n    if (n <= 1)\n        return false;\n    if (n == 2)\n        return true;\n    for (unsigned int i = 2; i <= sqrt(n); ++i)\n        if (n % i == 0)\n            return false;\n    return true;\n}\n"}
{"id": 44741, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "C++": "double Factorial(double nValue)\n   {\n       double result = nValue;\n       double result_next;\n       double pc = nValue;\n       do\n       {\n           result_next = result*(pc-1);\n           result = result_next;\n           pc--;\n       }while(pc>2);\n       nValue = result;\n       return nValue;\n   }\n\ndouble binomialCoefficient(double n, double k)\n   {\n       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;\n       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n       return Factorial(n) /(Factorial(k)*Factorial((n - k)));\n   }\n"}
{"id": 44742, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "C++": "int a[5]; \na[0] = 1; \n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \n\n#include <string>\nstd::string strings[4]; \n                        \n"}
{"id": 44743, "name": "Bitwise operations", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 44744, "name": "Read a file line by line", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 44745, "name": "Non-decimal radices_Convert", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 44746, "name": "Walk a directory_Recursively", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 44747, "name": "CRC-32", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 44748, "name": "Classes", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 44749, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44750, "name": "Kaprekar numbers", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44751, "name": "Anonymous recursion", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 44752, "name": "Create a file", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 44753, "name": "Delegates", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 44754, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44755, "name": "Command-line arguments", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44756, "name": "Array concatenation", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 44757, "name": "User input_Text", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 44758, "name": "Knapsack problem_0-1", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 44759, "name": "First-class functions", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 44760, "name": "Proper divisors", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 44761, "name": "Regular expressions", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 44762, "name": "Hash from two arrays", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 44763, "name": "Playing cards", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 44764, "name": "Arrays", "C#": " int[] numbers = new int[10];\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 44765, "name": "Sierpinski carpet", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 44766, "name": "Sorting algorithms_Bogosort", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 44767, "name": "Sequence of non-squares", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 44768, "name": "Substring", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 44769, "name": "Leap year", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 44770, "name": "Number names", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 44771, "name": "Compare length of two strings", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 44772, "name": "Letter frequency", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 44773, "name": "Increment a numerical string", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 44774, "name": "Strip a set of characters from a string", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 44775, "name": "Averages_Arithmetic mean", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 44776, "name": "Entropy", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 44777, "name": "Hello world_Text", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n", "PHP": "<?php\necho \"Hello world!\\n\";\n?>\n"}
{"id": 44778, "name": "Forward difference", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 44779, "name": "Primality by trial division", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 44780, "name": "Evaluate binomial coefficients", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 44781, "name": "Collections", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 44782, "name": "Bitmap_Write a PPM file", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 44783, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 44784, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 44785, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 44786, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 44787, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 44788, "name": "Read a file line by line", "Python": "for line in lines open('input.txt'):\n    print line\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 44789, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 44790, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 44791, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 44792, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 44793, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 44794, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 44795, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 44796, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 44797, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 44798, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44799, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44800, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44801, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44802, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44803, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44804, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 44805, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 44806, "name": "LZW compression", "Python": "def compress(uncompressed):\n    \n\n    \n    dict_size = 256\n    dictionary = dict((chr(i), i) for i in range(dict_size))\n    \n\n    w = \"\"\n    result = []\n    for c in uncompressed:\n        wc = w + c\n        if wc in dictionary:\n            w = wc\n        else:\n            result.append(dictionary[w])\n            \n            dictionary[wc] = dict_size\n            dict_size += 1\n            w = c\n\n    \n    if w:\n        result.append(dictionary[w])\n    return result\n\n\ndef decompress(compressed):\n    \n    from io import StringIO\n\n    \n    dict_size = 256\n    dictionary = dict((i, chr(i)) for i in range(dict_size))\n    \n\n    \n    \n    result = StringIO()\n    w = chr(compressed.pop(0))\n    result.write(w)\n    for k in compressed:\n        if k in dictionary:\n            entry = dictionary[k]\n        elif k == dict_size:\n            entry = w + w[0]\n        else:\n            raise ValueError('Bad compressed k: %s' % k)\n        result.write(entry)\n\n        \n        dictionary[dict_size] = w + entry[0]\n        dict_size += 1\n\n        w = entry\n    return result.getvalue()\n\n\n\ncompressed = compress('TOBEORNOTTOBEORTOBEORNOT')\nprint (compressed)\ndecompressed = decompress(compressed)\nprint (decompressed)\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 44807, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 44808, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 44809, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 44810, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44811, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44812, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44813, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44814, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44815, "name": "Substring_Top and tail", "Python": "print \"knight\"[1:]     \nprint \"socks\"[:-1]     \nprint \"brooms\"[1:-1]   \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44816, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 44817, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 44818, "name": "Longest string challenge", "Python": "import fileinput\n\n\n\n\n\n\ndef longer(a, b):\n    try:\n        b[len(a)-1]\n        return False\n    except:\n        return True\n\nlongest, lines = '', ''\nfor x in fileinput.input():\n    if longer(x, longest):\n        lines, longest = x, x\n    elif not longer(longest, x):\n        lines += x\n\nprint(lines, end='')\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 44819, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 44820, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 44821, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 44822, "name": "Sorting algorithms_Strand sort", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 44823, "name": "Sorting algorithms_Strand sort", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 44824, "name": "Sorting algorithms_Strand sort", "Python": "def merge_list(a, b):\n\tout = []\n\twhile len(a) and len(b):\n\t\tif a[0] < b[0]:\n\t\t\tout.append(a.pop(0))\n\t\telse:\n\t\t\tout.append(b.pop(0))\n\tout += a\n\tout += b\n\treturn out\n\ndef strand(a):\n\ti, s = 0, [a.pop(0)]\n\twhile i < len(a):\n\t\tif a[i] > s[-1]:\n\t\t\ts.append(a.pop(i))\n\t\telse:\n\t\t\ti += 1\n\treturn s\n\ndef strand_sort(a):\n\tout = strand(a)\n\twhile len(a):\n\t\tout = merge_list(out, strand(a))\n\treturn out\n\nprint strand_sort([1, 6, 3, 2, 1, 7, 5, 3])\n", "PHP": "$lst = new SplDoublyLinkedList();\nforeach (array(1,20,64,72,48,75,96,55,42,74) as $v)\n    $lst->push($v);\nforeach (strandSort($lst) as $v)\n    echo \"$v \";\n\nfunction strandSort(SplDoublyLinkedList $lst) {\n    $result = new SplDoublyLinkedList();\n    while (!$lst->isEmpty()) {\n        $sorted = new SplDoublyLinkedList();\n        $remain = new SplDoublyLinkedList();\n        $sorted->push($lst->shift());\n        foreach ($lst as $item) {\n            if ($sorted->top() <= $item) {\n                $sorted->push($item);\n            } else {\n                $remain->push($item);\n            }\n        }\n        $result = _merge($sorted, $result);\n        $lst = $remain;\n    }\n    return $result;\n}\n\nfunction _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {\n    $res = new SplDoublyLinkedList();\n    while (!$left->isEmpty() && !$right->isEmpty()) {\n        if ($left->bottom() <= $right->bottom()) {\n            $res->push($left->shift());\n        } else {\n            $res->push($right->shift());\n        }\n    }\n    foreach ($left as $v)  $res->push($v);\n    foreach ($right as $v) $res->push($v);\n    return $res;\n}\n"}
{"id": 44825, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 44826, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 44827, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "PHP": "class Delegator {\n  function __construct() {\n    $this->delegate = NULL ;\n  }\n  function operation() {\n    if(method_exists($this->delegate, \"thing\"))\n      return $this->delegate->thing() ;\n    return 'default implementation' ;\n  }\n}\n\nclass Delegate {\n  function thing() {\n    return 'Delegate Implementation' ;\n  }\n}\n\n$a = new Delegator() ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = 'A delegate may be any object' ;\nprint \"{$a->operation()}\\n\" ;\n\n$a->delegate = new Delegate() ;\nprint \"{$a->operation()}\\n\" ;\n"}
{"id": 44828, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44829, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44830, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44831, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44832, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44833, "name": "Abbreviations, easy", "Python": "command_table_text = \\\n\n\nuser_words = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n    \n    command_table = dict()\n    for word in command_table_text.split():\n        abbr_len = sum(1 for c in word if c.isupper())\n        if abbr_len == 0:\n            abbr_len = len(word)\n        command_table[word] = abbr_len\n    return command_table\n\ndef find_abbreviations(command_table):\n    \n    abbreviations = dict()\n    for command, min_abbr_len in command_table.items():\n        for l in range(min_abbr_len, len(command)+1):\n            abbr = command[:l].lower()\n            abbreviations[abbr] = command.upper()\n    return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n    user_words = [word.lower() for word in user_string.split()]\n    commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n    return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44834, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 44835, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 44836, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "PHP": "define(\"PI\", 3.14159265358);\ndefine(\"MSG\", \"Hello World\");\n"}
{"id": 44837, "name": "Sutherland-Hodgman polygon clipping", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 44838, "name": "Sutherland-Hodgman polygon clipping", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 44839, "name": "Sutherland-Hodgman polygon clipping", "Python": "def clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n", "PHP": "<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n"}
{"id": 44840, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 44841, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 44842, "name": "Call a foreign-language function", "Python": "import ctypes\nlibc = ctypes.CDLL(\"/lib/libc.so.6\")\nlibc.strcmp(\"abc\", \"def\")     \nlibc.strcmp(\"hello\", \"hello\") \n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 44843, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44844, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44845, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44846, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44847, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44848, "name": "Knuth's algorithm S", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n    sample, i = [], 0\n    def s_of_n(item):\n        nonlocal i\n\n        i += 1\n        if i <= n:\n            \n            sample.append(item)\n        elif randrange(i) < n:\n            \n            sample[randrange(n)] = item\n        return sample\n    return s_of_n\n\nif __name__ == '__main__':\n    bin = [0]* 10\n    items = range(10)\n    print(\"Single run samples for n = 3:\")\n    s_of_n = s_of_n_creator(3)\n    for item in items:\n        sample = s_of_n(item)\n        print(\"  Item: %i -> sample: %s\" % (item, sample))\n    \n    for trial in range(100000):\n        s_of_n = s_of_n_creator(3)\n        for item in items:\n            sample = s_of_n(item)\n        for s in sample:\n            bin[s] += 1\n    print(\"\\nTest item frequencies for 100000 runs:\\n \",\n          '\\n  '.join(\"%i:%i\" % x for x in enumerate(bin)))\n", "PHP": "<?php\nfunction s_of_n_creator($n) {\n    $sample = array();\n    $i = 0;\n    return function($item) use (&$sample, &$i, $n) {\n        $i++;\n        if ($i <= $n) {\n\n            $sample[] = $item;\n        } else if (rand(0, $i-1) < $n) {\n\n            $sample[rand(0, $n-1)] = $item;\n        }\n        return $sample;\n    };\n}\n\n$items = range(0, 9);\n\nfor ($trial = 0; $trial < 100000; $trial++) {\n    $s_of_n = s_of_n_creator(3);\n    foreach ($items as $item)\n        $sample = $s_of_n($item);\n    foreach ($sample as $s)\n        $bin[$s]++;\n}\nprint_r($bin);\n?>\n"}
{"id": 44849, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44850, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44851, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44852, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44853, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44854, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44855, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 44856, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 44857, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 44858, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 44859, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 44860, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 44861, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 44862, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 44863, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 44864, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 44865, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 44866, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "PHP": "$compose = function ($f, $g) {\n    return function ($x) use ($f, $g) {\n        return $f($g($x));\n    };\n};\n\n$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });\n$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });\n\nfor ($i = 0; $i < 3; $i++) {\n    $f = $compose($inv[$i], $fn[$i]);\n    echo $f(0.5), PHP_EOL;\n}\n"}
{"id": 44867, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 44868, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 44869, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 44870, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 44871, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 44872, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 44873, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 44874, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 44875, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 44876, "name": "Fractal tree", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 44877, "name": "Fractal tree", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 44878, "name": "Fractal tree", "Python": "def setup():\n    size(600, 600)\n    background(0)\n    stroke(255)\n    drawTree(300, 550, 9)\n    \ndef drawTree(x, y, depth):\n    fork_ang = radians(20)\n    base_len = 10\n    if depth > 0:\n        pushMatrix()\n        translate(x, y - baseLen * depth)\n        line(0, baseLen * depth, 0, 0)  \n        rotate(fork_ang)\n        drawTree(0, 0, depth - 1)  \n        rotate(2 * -fork_ang)\n        drawTree(0, 0, depth - 1) \n        popMatrix()\n", "PHP": "<?php\nheader(\"Content-type: image/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n"}
{"id": 44879, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44880, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44881, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44882, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44883, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44884, "name": "Gray code", "Python": ">>> def int2bin(n):\n\t'From positive integer to list of binary bits, msb at index 0'\n\tif n:\n\t\tbits = []\n\t\twhile n:\n\t\t\tn,remainder = divmod(n, 2)\n\t\t\tbits.insert(0, remainder)\n\t\treturn bits\n\telse: return [0]\n\n\t\n>>> def bin2int(bits):\n\t'From binary bits, msb at index 0 to integer'\n\ti = 0\n\tfor bit in bits:\n\t\ti = i * 2 + bit\n\treturn i\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44885, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 44886, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 44887, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 44888, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint(array[0])\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 44889, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint(array[0])\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 44890, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint(array[0])\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 44891, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 44892, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 44893, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 44894, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 44895, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 44896, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 44897, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 44898, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 44899, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 44900, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 44901, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 44902, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 44903, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 44904, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 44905, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 44906, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 44907, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 44908, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 44909, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 44910, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 44911, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "PHP": "<?php\n\n\nfunction retrieveStrings()\n{\n    if (isset($_POST['input'])) {\n        $strings = explode(\"\\n\", $_POST['input']);\n    } else {\n        $strings = ['abcd', '123456789', 'abcdef', '1234567'];\n    }\n    return $strings;\n}\n\n\nfunction setInput()\n{\n    echo join(\"\\n\", retrieveStrings());\n}\n\n\nfunction setOutput()\n{\n    $strings = retrieveStrings();\n\n\n    $strings = array_map('trim', $strings);\n    $strings = array_filter($strings);\n\n    if (!empty($strings)) {\n        usort($strings, function ($a, $b) {\n            return strlen($b) - strlen($a);\n        });\n        $max_len = strlen($strings[0]);\n        $min_len = strlen($strings[count($strings) - 1]);\n        foreach ($strings as $s) {\n            $length = strlen($s);\n            if ($length == $max_len) {\n                $predicate = \"is the longest string\";\n            } elseif ($length == $min_len) {\n                $predicate = \"is the shortest string\";\n            } else {\n                $predicate = \"is neither the longest nor the shortest string\";\n            }\n            echo \"$s has length $length and $predicate\\n\";\n        }\n    }\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <style>\n        div {\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n\n        label {\n            display: block;\n            margin-bottom: 1ch;\n        }\n\n        textarea {\n            display: block;\n        }\n\n        input {\n            display: block;\n            margin-top: 4ch;\n            margin-bottom: 4ch;\n        }\n    </style>\n</head>\n\n\n<body>\n    <main>\n        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method=\"post\" accept-charset=\"utf-8\">\n            <div>\n                <label for=\"input\">Input:\n                </label>\n                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>\n                </label>\n            </div>\n            <input type=\"submit\" value=\"press to compare strings\">\n            </input>\n            <div>\n                <label for=\"Output\">Output:\n                </label>\n                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>\n            </div>\n        </form>\n    </main>\n</body>\n\n</html>\n"}
{"id": 44912, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 44913, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 44914, "name": "Sorting algorithms_Shell sort", "Python": "def shell(seq):\n    inc = len(seq) // 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 // 11\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 44915, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 44916, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 44917, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 44918, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 44919, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 44920, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 44921, "name": "Sorting algorithms_Permutation sort", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 44922, "name": "Sorting algorithms_Permutation sort", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 44923, "name": "Sorting algorithms_Permutation sort", "Python": "from itertools import permutations\n\nin_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))\nperm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()\n", "PHP": "function inOrder($arr){\n\tfor($i=0;$i<count($arr);$i++){\n\t\tif(isset($arr[$i+1])){\n\t\t\tif($arr[$i] > $arr[$i+1]){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction permute($items, $perms = array( )) {\n    if (empty($items)) {\n\t\tif(inOrder($perms)){\n\t\t\treturn $perms;\n\t\t}\n    }  else {\n        for ($i = count($items) - 1; $i >= 0; --$i) {\n             $newitems = $items;\n             $newperms = $perms;\n             list($foo) = array_splice($newitems, $i, 1);\n             array_unshift($newperms, $foo);\n             $res = permute($newitems, $newperms);\n\t\t\t if($res){\n\t\t\t\treturn $res;\n\t\t\t }\t\t \t\t \n         }\n    }\n}\n\n$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);\n$arr = permute($arr);\necho implode(',',$arr);\n"}
{"id": 44924, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 44925, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 44926, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 44927, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 44928, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 44929, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "PHP": "<?php\n\nfunction shannonEntropy($string) {\n    $h = 0.0;\n    $len = strlen($string);\n    foreach (count_chars($string, 1) as $count) {\n        $h -= (double) ($count / $len) * log((double) ($count / $len), 2);\n    }\n    return $h;\n}\n\n$strings = array(\n    '1223334444',\n    '1225554444',\n    'aaBBcccDDDD',\n    '122333444455555',\n    'Rosetta Code',\n    '1234567890abcdefghijklmnopqrstuvwxyz',\n);\n\nforeach ($strings AS $string) {\n    printf(\n        '%36s : %s' . PHP_EOL,\n        $string,\n        number_format(shannonEntropy($string), 6)\n    );\n}\n"}
{"id": 44930, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 44931, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 44932, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 44933, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 44934, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 44935, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 44936, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 44937, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 44938, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 44939, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 44940, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 44941, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 44942, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 44943, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 44944, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "PHP": "class Bitmap {\n  public $data;\n  public $w;\n  public $h;\n  public function __construct($w = 16, $h = 16){\n    $white = array_fill(0, $w, array(255,255,255));\n    $this->data = array_fill(0, $h, $white);\n    $this->w = $w;\n    $this->h = $h;\n  }\n\n  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){\n    if (is_null($w)) $w = $this->w;\n    if (is_null($h)) $h = $this->h;\n    $w += $x;\n    $h += $y;\n    for ($i = $y; $i < $h; $i++){\n      for ($j = $x; $j < $w; $j++){\n        $this->setPixel($j, $i, $color);\n      }\n    }\n  }\n  public function setPixel($x, $y, $color = array(0,0,0)){\n    if ($x >= $this->w) return false;\n    if ($x < 0) return false;\n    if ($y >= $this->h) return false;\n    if ($y < 0) return false;\n    $this->data[$y][$x] = $color;\n  }\n  public function getPixel($x, $y){\n    return $this->data[$y][$x];\n  }\n  public function writeP6($filename){\n    $fh = fopen($filename, 'w');\n    if (!$fh) return false;\n    fputs($fh, \"P6 {$this->w} {$this->h} 255\\n\");\n    foreach ($this->data as $row){\n      foreach($row as $pixel){\n        fputs($fh, pack('C', $pixel[0]));\n        fputs($fh, pack('C', $pixel[1]));\n        fputs($fh, pack('C', $pixel[2]));\n      }\n    }\n    fclose($fh);\n  }\n}\n\n$b = new Bitmap(16,16);\n$b->fill();\n$b->fill(2, 2, 18, 18, array(240,240,240));\n$b->setPixel(0, 15, array(255,0,0));\n$b->writeP6('p6.ppm');\n"}
{"id": 44945, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 44946, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 44947, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "PHP": "<?php\nunlink('input.txt');\nunlink('/input.txt');\nrmdir('docs');\nrmdir('/docs');\n?>\n"}
{"id": 44948, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n"}
{"id": 44949, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n"}
{"id": 44950, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "PHP": "<?php\n    $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);\n    $MONTHS = array(\"Choas\",\"Discord\",\"Confusion\",\"Bureacracy\",\"The Aftermath\");\n    $DAYS = array(\"Setting Orange\",\"Sweetmorn\",\"BoomTime\",\"Pungenday\",\"Prickle-Prickle\");\n    $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');\n    $Holy5 = array(\"Mungday\",\"MojoDay\",\"Syaday\",\"Zaraday\",\"Maladay\");\n    $Holy50 = array(\"Chaoflux\",\"Discoflux\",\"Confuflux\",\"Bureflux\",\"Afflux\");\n\n\t$edate = explode(\" \",date('Y m j L'));\n\t$usery = $edate[0];\n\t$userm = $edate[1];\n\t$userd = $edate[2];\n\t$IsLeap = $edate[3];\n\n\n\n\n\n\n    if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {\n        $usery = $_GET['y'];\n        $userm = $_GET['m'];\n        $userd = $_GET['d'];\n        $IsLeap = 0;\n        if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;\n        if ($usery%400 == 0) $IsLeap = 1;\n    }\n\n\n    $userdays = 0;\n    $i = 0;\n    while ($i < ($userm-1)) {\n        \n        $userdays = $userdays + $Anerisia[$i];\n        $i = $i +1;\n    }\n    $userdays = $userdays + $userd;\n\n\n\n\n\n\n    $IsHolyday = 0;\n    $dyear = $usery + 1166;\n    $dmonth = $MONTHS[$userdays/73.2];\n    $dday = $userdays%73;\n\tif (0 == $dday) $dday = 73;\n    $Dname = $DAYS[$userdays%5];\n    $Holyday = \"St. Tibs Day\";\n    if ($dday == 5) {\n        $Holyday = $Holy5[$userdays/73.2];\n        $IsHolyday =1;\n    }\n    if ($dday == 50) {\n        $Holyday = $Holy50[$userdays/73.2];\n        $IsHolyday =1;\n    }\n\n  if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;\n\n   $suff = $Dsuff[$dday%10] ;\n   if ((11 <= $dday) && (19 >= $dday)) $suff='th';\n\n\n if ($IsHolyday ==2)\n      echo \"</br>Celeberate \",$Holyday,\" \",$dmonth,\" YOLD \",$dyear;\n    if ($IsHolyday ==1)\n      echo \"</br>Celeberate for today \", $Dname , \" The \", $dday,\"<sup>\",$suff,\"</sup>\", \" day of \", $dmonth , \" YOLD \" , $dyear , \" is the holy day of \" , $Holyday;\n    if ($IsHolyday == 0)\n       echo \"</br>Today is \" , $Dname , \" the \" , $dday ,\"<sup>\",$suff, \"</sup> day of \" , $dmonth , \" YOLD \" , $dyear;\n\n ?>\n"}
{"id": 44951, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 44952, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 44953, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "PHP": "<?php\n$extra = 'little';\necho \"Mary had a $extra lamb.\\n\";\nprintf(\"Mary had a %s lamb.\\n\", $extra);\n?>\n"}
{"id": 44954, "name": "Sorting algorithms_Patience sort", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n"}
{"id": 44955, "name": "Sorting algorithms_Patience sort", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n"}
{"id": 44956, "name": "Sorting algorithms_Patience sort", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n    def __lt__(self, other): return self[-1] < other[-1]\n    def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n    piles = []\n    \n    for x in n:\n        new_pile = Pile([x])\n        i = bisect_left(piles, new_pile)\n        if i != len(piles):\n            piles[i].append(x)\n        else:\n            piles.append(new_pile)\n\n    \n    n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n    a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n    patience_sort(a)\n    print a\n", "PHP": "<?php\nclass PilesHeap extends SplMinHeap {\n    public function compare($pile1, $pile2) {\n        return parent::compare($pile1->top(), $pile2->top());\n    }\n}\n\nfunction patience_sort(&$n) {\n    $piles = array();\n\n    foreach ($n as $x) {\n\n        $low = 0; $high = count($piles)-1;\n        while ($low <= $high) {\n            $mid = (int)(($low + $high) / 2);\n            if ($piles[$mid]->top() >= $x)\n                $high = $mid - 1;\n            else\n                $low = $mid + 1;\n        }\n        $i = $low;\n        if ($i == count($piles))\n            $piles[] = new SplStack();\n        $piles[$i]->push($x);\n    }\n\n    $heap = new PilesHeap();\n    foreach ($piles as $pile)\n        $heap->insert($pile);\n    for ($c = 0; $c < count($n); $c++) {\n        $smallPile = $heap->extract();\n        $n[$c] = $smallPile->pop();\n        if (!$smallPile->isEmpty())\n        $heap->insert($smallPile);\n    }\n    assert($heap->isEmpty());\n}\n\n$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);\npatience_sort($a);\nprint_r($a);\n?>\n"}
{"id": 44957, "name": "Wireworld", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n"}
{"id": 44958, "name": "Wireworld", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n"}
{"id": 44959, "name": "Wireworld", "Python": "\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO()\n\ndef readfile(f):\n    \n    world  = [row.rstrip('\\r\\n') for row in f]\n    height = len(world)\n    width  = max(len(row) for row in world)\n    \n    nonrow = [ \" %*s \" % (-width, \"\") ]\n    world  = nonrow + \\\n               [ \" %*s \" % (-width, row) for row in world ] + \\\n               nonrow   \n    world = [list(row) for row in world]\n    return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n    istate = currentworld[y][x]\n    assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n    if istate == head:\n        ostate = tail\n    elif istate == tail:\n        ostate = conductor\n    elif istate == empty:\n        ostate = empty\n    else: \n        n = sum( currentworld[y+dy][x+dx] == head\n                 for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n                                (+0,-1),          (+0,+1),\n                                (+1,-1), (+1,+0), (+1,+1) ) )\n        ostate = head if 1 <= n <= 2 else conductor\n    return ostate\n\ndef nextgen(ww):\n    'compute next generation of wireworld'\n    world, width, height = ww\n    newworld = copy.deepcopy(world)\n    for x in range(1, width+1):\n        for y in range(1, height+1):\n            newworld[y][x] = newcell(world, x, y)\n    return WW(newworld, width, height)\n\ndef world2string(ww):\n    return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n    print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n    print ( world2string(ww) )\n    ww = nextgen(ww)\n", "PHP": "$desc = 'tH.........\n.   .\n  ........\n.   .\nHt.. ......\n\n      ..\ntH.... .......\n      ..\n\n      ..\ntH..... ......\n      ..';\n\n$steps = 30;\n\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n    switch($i){\n        case \"\\n\":\n            $row++;\n\n            $col = 0;\n            $world[] = array();\n            break;\n        case '.':\n            $world[$row][$col] = 1;//conductor\n            $col++;\n            break;\n        case 'H':\n            $world[$row][$col] = 2;//head\n            $col++;\n            break;\n        case 't':\n            $world[$row][$col] = 3;//tail\n            $col++;\n            break;\n        default:\n            $world[$row][$col] = 0;//insulator/air\n            $col++;\n            break;\n    };\n};\nfunction draw_world($world){\n    foreach($world as $rowc){\n        foreach($rowc as $cell){\n            switch($cell){\n                case 0:\n                    echo ' ';\n                    break;\n                case 1:\n                    echo '.';\n                    break;\n                case 2:\n                    echo 'H';\n                    break;\n                case 3:\n                    echo 't';\n            };\n        };\n        echo \"\\n\";\n    };\n\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n    $old_world = $world; //backup to look up where was an electron head\n    foreach($world as $row => &$rowc){\n        foreach($rowc as $col => &$cell){\n            switch($cell){\n                case 2:\n                    $cell = 3;\n                    break;\n                case 3:\n                    $cell = 1;\n                    break;\n                case 1:\n                    $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n                    $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n                    $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n                    if($neigh_heads == 1 || $neigh_heads == 2){\n                        $cell = 2;\n                    };\n            };\n        };\n        unset($cell); //just to be safe\n    };\n    unset($rowc); //just to be safe\n    echo \"\\nStep \" . ($i + 1) . \":\\n\";\n    draw_world($world);\n};\n"}
{"id": 44960, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n"}
{"id": 44961, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n"}
{"id": 44962, "name": "Ray-casting algorithm", "Python": "from collections import namedtuple\nfrom pprint import pprint as pp\nimport sys\n\nPt = namedtuple('Pt', 'x, y')               \nEdge = namedtuple('Edge', 'a, b')           \nPoly = namedtuple('Poly', 'name, edges')    \n\n_eps = 0.00001\n_huge = sys.float_info.max\n_tiny = sys.float_info.min\n\ndef rayintersectseg(p, edge):\n    \n    a,b = edge\n    if a.y > b.y:\n        a,b = b,a\n    if p.y == a.y or p.y == b.y:\n        p = Pt(p.x, p.y + _eps)\n\n    intersect = False\n\n    if (p.y > b.y or p.y < a.y) or (\n        p.x > max(a.x, b.x)):\n        return False\n\n    if p.x < min(a.x, b.x):\n        intersect = True\n    else:\n        if abs(a.x - b.x) > _tiny:\n            m_red = (b.y - a.y) / float(b.x - a.x)\n        else:\n            m_red = _huge\n        if abs(a.x - p.x) > _tiny:\n            m_blue = (p.y - a.y) / float(p.x - a.x)\n        else:\n            m_blue = _huge\n        intersect = m_blue >= m_red\n    return intersect\n\ndef _odd(x): return x%2 == 1\n\ndef ispointinside(p, poly):\n    ln = len(poly)\n    return _odd(sum(rayintersectseg(p, edge)\n                    for edge in poly.edges ))\n\ndef polypp(poly):\n    print (\"\\n  Polygon(name='%s', edges=(\" % poly.name)\n    print ('   ', ',\\n    '.join(str(e) for e in poly.edges) + '\\n    ))')\n\nif __name__ == '__main__':\n    polys = [\n      Poly(name='square', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))\n        )),\n      Poly(name='square_hole', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),\n        Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='strange', edges=(\n        Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),\n        Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),\n        Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),\n        Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),\n        Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),\n        Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),\n        Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))\n        )),\n      Poly(name='exagon', edges=(\n        Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),\n        Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),\n        Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),\n        Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),\n        Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),\n        Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))\n        )),\n      ]\n    testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),\n                  Pt(x=-10, y=5), Pt(x=0, y=5),\n                  Pt(x=10, y=5), Pt(x=8, y=5),\n                  Pt(x=10, y=10))\n    \n    print (\"\\n TESTING WHETHER POINTS ARE WITHIN POLYGONS\")\n    for poly in polys:\n        polypp(poly)\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[:3]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[3:6]))\n        print ('   ', '\\t'.join(\"%s: %s\" % (p, ispointinside(p, poly))\n                               for p in testpoints[6:]))\n", "PHP": "<?php\n\nfunction contains($bounds, $lat, $lng)\n{\n    $count = 0;\n    $bounds_count = count($bounds);\n    for ($b = 0; $b < $bounds_count; $b++) {\n        $vertex1 = $bounds[$b];\n        $vertex2 = $bounds[($b + 1) % $bounds_count];\n        if (west($vertex1, $vertex2, $lng, $lat))\n            $count++;\n    }\n\n    return $count % 2;\n}\n\nfunction west($A, $B, $x, $y)\n{\n    if ($A['y'] <= $B['y']) {\n        if ($y <= $A['y'] || $y > $B['y'] ||\n            $x >= $A['x'] && $x >= $B['x']) {\n            return false;\n        }\n        if ($x < $A['x'] && $x < $B['x']) {\n            return true;\n        }\n        if ($x == $A['x']) {\n            if ($y == $A['y']) {\n                $result1 = NAN;\n            } else {\n                $result1 = INF;\n            }\n        } else {\n            $result1 = ($y - $A['y']) / ($x - $A['x']);\n        }\n        if ($B['x'] == $A['x']) {\n            if ($B['y'] == $A['y']) {\n                $result2 = NAN;\n            } else {\n                $result2 = INF;\n            }\n        } else {\n            $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);\n        }\n        return $result1 > $result2;\n    }\n\n    return west($B, $A, $x, $y);\n}\n\n$square = [\n    'name' => 'square',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]\n];\n$squareHole = [\n    'name' => 'squareHole',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]\n];\n$strange = [\n    'name' => 'strange',\n    'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]\n];\n$hexagon = [\n    'name' => 'hexagon',\n    'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]\n];\n \n$shapes = [$square, $squareHole, $strange, $hexagon];\n\n$testPoints = [\n    ['lng' => 10, 'lat' => 10],\n    ['lng' => 10, 'lat' => 16],\n    ['lng' => -20, 'lat' => 10],\n    ['lng' => 0, 'lat' => 10],\n    ['lng' => 20, 'lat' => 10],\n    ['lng' => 16, 'lat' => 10],\n    ['lng' => 20, 'lat' => 20]\n];\n \nfor ($s = 0; $s < count($shapes); $s++) {\n    $shape = $shapes[$s];\n    for ($tp = 0; $tp < count($testPoints); $tp++) {\n        $testPoint = $testPoints[$tp];\n        echo json_encode($testPoint) . \"\\tin \" . $shape['name'] . \"\\t\" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;\n    }\n}\n"}
{"id": 44963, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 44964, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 44965, "name": "Count occurrences of a substring", "Python": ">>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n", "PHP": "<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; // prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; // prints \"2\"\n"}
{"id": 44966, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open(\"notes.txt\", \"r\") as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open(\"notes.txt\", \"a\") as f:\n        f.write(datetime.datetime.now().isoformat() + \"\\n\")\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "PHP": "#!/usr/bin/php\n<?php\nif ($argc > 1)\n    file_put_contents(\n        'notes.txt', \n        date('r').\"\\n\\t\".implode(' ', array_slice($argv, 1)).\"\\n\",\n        FILE_APPEND\n    );\nelse\n    @readfile('notes.txt');\n"}
{"id": 44967, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open(\"notes.txt\", \"r\") as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open(\"notes.txt\", \"a\") as f:\n        f.write(datetime.datetime.now().isoformat() + \"\\n\")\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "PHP": "#!/usr/bin/php\n<?php\nif ($argc > 1)\n    file_put_contents(\n        'notes.txt', \n        date('r').\"\\n\\t\".implode(' ', array_slice($argv, 1)).\"\\n\",\n        FILE_APPEND\n    );\nelse\n    @readfile('notes.txt');\n"}
{"id": 44968, "name": "Bitwise operations", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n", "PHP": "function bitwise($a, $b)\n{\n    function zerofill($a,$b) { \n        if($a>=0) return $a>>$b;\n        if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with \"if($b==0) return $a;\" if you need $b=0 to mean that nothing happens\n        return ((~$a)>>$b)^(0x7fffffff>>($b-1)); \n\n    echo '$a AND $b: ' . $a & $b . '\\n';\n    echo '$a OR $b: ' . $a | $b . '\\n';\n    echo '$a XOR $b: ' . $a ^ $b . '\\n';\n    echo 'NOT $a: ' . ~$a . '\\n';\n    echo '$a << $b: ' . $a << $b . '\\n'; // left shift  \n    echo '$a >> $b: ' . $a >> $b . '\\n'; // arithmetic right shift\n    echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\\n'; // logical right shift\n}\n"}
{"id": 44969, "name": "Read a file line by line", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n", "PHP": "<?php\n$file = fopen(__FILE__, 'r'); // read current file\nwhile ($line = fgets($file)) {\n    $line = rtrim($line);      // removes linebreaks and spaces at end\n    echo strrev($line) . \"\\n\"; // reverse line and upload it\n}\n"}
{"id": 44970, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "PHP": "base_convert(\"26\", 10, 16); // returns \"1a\"\n"}
{"id": 44971, "name": "Walk a directory_Recursively", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n", "PHP": "function findFiles($dir = '.', $pattern = '/./'){\n  $prefix = $dir . '/';\n  $dir = dir($dir);\n  while (false !== ($file = $dir->read())){\n    if ($file === '.' || $file === '..') continue;\n    $file = $prefix . $file;\n    if (is_dir($file)) findFiles($file, $pattern);\n    if (preg_match($pattern, $file)){\n      echo $file . \"\\n\";\n    }\n  }\n}\nfindFiles('./foo', '/\\.bar$/');\n"}
{"id": 44972, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "PHP": "printf(\"%x\\n\", crc32(\"The quick brown fox jumps over the lazy dog\"));\n"}
{"id": 44973, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "PHP": "class MyClass {\n    public static $classVar;\n    public $instanceVar; // can also initialize it here\n    function __construct() {\n        $this->instanceVar = 0;\n    }\n    function someMethod() {\n        $this->instanceVar = 1;\n        self::$classVar = 3;\n    }\n}\n$myObj = new MyClass();\n"}
{"id": 44974, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44975, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "PHP": "set_time_limit(300);\n\nprint_r(array_filter(range(1, 10000), 'isKaprekar'));\necho count(array_filter(range(1, 1000000), 'isKaprekar'));\n\nfunction isKaprekar($n) {\n    $a = $n * $n; \n    $b = bcmod(\"$a\", \"10\");\n    for ($d = 1, $t = 0; $a > 0; $d *= 10) {\n        $b += $t * $d;\n        if ($b > $n) break;\n        $a = floor($a / 10);\n        if ($b && $a + $b == $n) \n            return true;\n        $t = bcmod(\"$a\", \"10\");\n    }\n    return false;\n}\n"}
{"id": 44976, "name": "LZW compression", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n", "PHP": "class LZW\n{\n    function compress($unc) {\n        $i;$c;$wc;\n        $w = \"\";\n        $dictionary = array();\n        $result = array();\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i += 1) {\n            $dictionary[chr($i)] = $i;\n        }\n        for ($i = 0; $i < strlen($unc); $i++) {\n            $c = $unc[$i];\n            $wc = $w.$c;\n            if (array_key_exists($w.$c, $dictionary)) {\n                $w = $w.$c;\n            } else {\n                array_push($result,$dictionary[$w]);\n                $dictionary[$wc] = $dictSize++;\n                $w = (string)$c;\n            }\n        }\n        if ($w !== \"\") {\n            array_push($result,$dictionary[$w]);\n        }\n        return implode(\",\",$result);\n    }\n\n    function decompress($com) {\n        $com = explode(\",\",$com);\n        $i;$w;$k;$result;\n        $dictionary = array();\n        $entry = \"\";\n        $dictSize = 256;\n        for ($i = 0; $i < 256; $i++) {\n            $dictionary[$i] = chr($i);\n        }\n        $w = chr($com[0]);\n        $result = $w;\n        for ($i = 1; $i < count($com);$i++) {\n            $k = $com[$i];\n            if (isset($dictionary[$k])) {\n                $entry = $dictionary[$k];\n            } else {\n                if ($k === $dictSize) {\n                    $entry = $w.$w[0];\n                } else {\n                    return null;\n                }\n            }\n            $result .= $entry;\n            $dictionary[$dictSize++] = $w . $entry[0];\n            $w = $entry;\n        }\n        return $result;\n    }\n}\n\n$str = 'TOBEORNOTTOBEORTOBEORNOT';\n$lzw = new LZW();\n$com = $lzw->compress($str);\n$dec = $lzw->decompress($com);\necho $com . \"<br>\" . $dec;\n"}
{"id": 44977, "name": "Anonymous recursion", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n", "PHP": "<?php\nfunction fib($n) {\n    if ($n < 0)\n        throw new Exception('Negative numbers not allowed');\n    $f = function($n) { // This function must be called using call_user_func() only\n        if ($n < 2)\n            return 1;\n        else {\n            $g = debug_backtrace()[1]['args'][0];\n            return call_user_func($g, $n-1) + call_user_func($g, $n-2);\n        }\n    };\n    return call_user_func($f, $n);\n}\necho fib(8), \"\\n\";\n?>\n"}
{"id": 44978, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44979, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "PHP": "<?php\necho substr(\"knight\", 1), \"\\n\";       // strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    // strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   // strip both first and last characters\n?>\n"}
{"id": 44980, "name": "Longest string challenge", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n", "PHP": "<?php\n\necho 'Enter strings (empty string to finish) :', PHP_EOL;\n\n$output = $previous = readline();\nwhile ($current = readline()) {\n    $p = $previous;\n    $c = $current;\n\n    while ($p and $c) {\n        $p = substr($p, 1);\n        $c = substr($c, 1);\n    }\n\n    if (!$p and !$c) {\n        $output .= PHP_EOL . $current;\n    }\n\n    if ($c) {\n        $output = $previous = $current;\n    }\n}\n\necho 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;\n"}
{"id": 44981, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "PHP": "<?php\ntouch('output.txt');\nmkdir('docs');\ntouch('/output.txt');\nmkdir('/docs');\n?>\n"}
{"id": 44982, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44983, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "PHP": "\n$commands = 'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\n   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\n   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\n   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\n   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up';\n\n$input = 'riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin';\n$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';\n$table = makeCommandTable($commands);\n$table_keys = array_keys($table);\n\n$inputTable = processInput($input);\n\nforeach ($inputTable as $word) {\n    $rs = searchCommandTable($word, $table);\n    if ($rs) {\n        $output[] = $rs;\n    } else {\n        $output[] = '*error*';\n    }\n\n}\necho 'Input: '. $input. PHP_EOL;\necho 'Output: '. implode(' ', $output). PHP_EOL;\n\nfunction searchCommandTable($search, $table) {\n    foreach ($table as $key => $value) {\n        if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {\n            return $key;\n        }\n    }\n    return false;\n}\n\nfunction processInput($input) {\n    $input = preg_replace('!\\s+!', ' ', $input);\n    $pieces = explode(' ', trim($input));\n    return $pieces;\n}\n\nfunction makeCommandTable($commands) {\n    $commands = preg_replace('!\\s+!', ' ', $commands);\n    $pieces = explode(' ', trim($commands));\n    foreach ($pieces as $word) {\n        $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all(\"/[A-Z]/\", $word)];\n    }\n    return $rs;\n}\n"}
{"id": 44984, "name": "Call a foreign-language function", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n", "PHP": "$ffi = FFI::cdef(\"char *_strdup(const char *strSource);\", \"msvcrt.dll\");\n\n$cstr = $ffi->_strdup(\"success\");\n$str = FFI::string($cstr);\necho $str;\nFFI::free($cstr);\n"}
{"id": 44985, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44986, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "PHP": "<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n"}
{"id": 44987, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "PHP": "$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n"}
{"id": 44988, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "PHP": "#!/usr/bin/php\n<?php\n$string = fgets(STDIN);\n$integer = (int) fgets(STDIN);\n"}
{"id": 44989, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "PHP": "#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\n\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { // Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; // Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); // and the picked item\n\t\t\t\treturn array($v[$i],array($i)); // Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\n\t\t\t\t$m[$i][$aW] = 0; // Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); // and a blank array entry...\n\t\t\t\treturn array(0,array()); // Return nothing\n\t\t\t}\n\t\t}\t\n\n\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { // Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; // Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); // and return it\n\n\t\t} else {\n\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  // ..and add the value of this one..\n\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; // Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; // and store the picked item\n\t\t\treturn array ($res,$picked); // and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:</b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:</b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:</b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item</td><td>Value</td><td>Weight</td></tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"</td><td>\".$v4[$key].\"</td><td>\".$w4[$key].\"</td></tr>\";\n}\necho \"<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>\";\necho \"</table><hr>\";\n"}
{"id": 44990, "name": "Proper divisors", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n", "PHP": "<?php\nfunction ProperDivisors($n) {\n  yield 1;\n  $large_divisors = [];\n  for ($i = 2; $i <= sqrt($n); $i++) {\n    if ($n % $i == 0) {\n      yield $i;\n      if ($i*$i != $n) {\n        $large_divisors[] = $n / $i;\n      }\n    }\n  }\n  foreach (array_reverse($large_divisors) as $i) {\n    yield $i;\n  }\n}\n\nassert([1, 2, 4, 5, 10, 20, 25, 50] ==\n        iterator_to_array(ProperDivisors(100)));\n\nforeach (range(1, 10) as $n) {\n  echo \"$n =>\";\n  foreach (ProperDivisors($n) as $divisor) {\n    echo \" $divisor\";\n  }\n  echo \"\\n\";\n}\n\n$divisorsCount = [];\nfor ($i = 1; $i < 20000; $i++) {\n  $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;\n}\nksort($divisorsCount);\n\necho \"Numbers with most divisors: \", implode(\", \", end($divisorsCount)), \".\\n\";\necho \"They have \", key($divisorsCount), \" divisors.\\n\";\n"}
{"id": 44991, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "PHP": "$string = 'I am a string';\n# Test\nif (preg_match('/string$/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('/\\ba\\b/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n"}
{"id": 44992, "name": "Hash from two arrays", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n", "PHP": "$keys = array('a', 'b', 'c');\n$values = array(1, 2, 3);\n$hash = array_combine($keys, $values);\n"}
{"id": 44993, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44994, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "PHP": "<?php\n\n\n\n\nfunction gray_encode($binary){\n\treturn $binary ^ ($binary >> 1);\n}\n\n\nfunction gray_decode($gray){\n\t$binary = $gray;\n\twhile($gray >>= 1) $binary ^= $gray;\n\treturn $binary;\n}\n\nfor($i=0;$i<32;$i++){\n\t$gray_encoded = gray_encode($i);\n\tprintf(\"%2d : %05b => %05b => %05b : %2d \\n\",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));\n}\n"}
{"id": 44995, "name": "Playing cards", "VB": "suite$ = \"CDHS\"                 #Club, Diamond, Heart, Spade\ncard$  = \"A23456789TJQK\"        #Cards Ace to King\ncard   = 0\n\ndim n(55)                       #make ordered deck\nfor i = 1 to 52                 # of 52 cards\n    n[i] = i\nnext i\n\nfor i = 1 to 52 * 3             #shuffle deck 3 times\n    i1    = int(rand * 52) + 1\n    i2    = int(rand * 52) + 1\n    h2    = n[i1]\n    n[i1] = n[i2]\n    n[i2] = h2\nnext i\n\nfor hand = 1 to 4               #4 hands\n    for deal = 1 to 13            #deal each 13 cards\n        card += 1               #next card in deck\n        s = (n[card] mod 4)  + 1    #determine suite\n        c = (n[card] mod 13) + 1    #determine card\n        print mid(card$,c,1);mid(suite$,s,1);\" \";  #show the card\n    next deal\n    print\nnext hand\nend\n\nfunction word$(sr$, wn, delim$)\n    j = wn\n    if j = 0 then j += 1\n    res$ = \"\" : s$ = sr$ : d$ = delim$\n    if d$ = \"\" then d$ = \" \"\n    sd = length(d$) : sl = length(s$)\n    while true\n        n = instr(s$,d$) : j -= 1\n        if j = 0 then\n            if n=0 then res$=s$ else res$=mid(s$,1,n-1)\n            return res$\n        end if\n        if n = 0 then return res$\n        if n = sl - sd then res$ = \"\" : return res$\n        sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2\n    end while\n    return res$\nend function\n", "PHP": "class Card\n{\n\n    protected static $suits = array( '♠', '♥', '♦', '♣' );\n\n    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\n    protected $suit;\n\n    protected $suitOrder;\n\n    protected $pip;\n\n    protected $pipOrder;\n\n    protected $order;\n\n    public function __construct( $suit, $pip )\n    {\n        if( !in_array( $suit, self::$suits ) )\n        {\n            throw new InvalidArgumentException( 'Invalid suit' );\n        }\n        if( !in_array( $pip, self::$pips ) )\n        {\n            throw new InvalidArgumentException( 'Invalid pip' );\n        }\n\n        $this->suit = $suit;\n        $this->pip = $pip;\n    }\n\n    public function getSuit()\n    {\n        return $this->suit;\n    }\n\n    public function getPip()\n    {\n        return $this->pip;\n    }\n\n    public function getSuitOrder()\n    {\n\n        if( !isset( $this->suitOrder ) )\n        {\n\n            $this->suitOrder = array_search( $this->suit, self::$suits );\n        }\n\n        return $this->suitOrder;\n    }\n\n    public function getPipOrder()\n    {\n\n        if( !isset( $this->pipOrder ) )\n        {\n\n            $this->pipOrder = array_search( $this->pip, self::$pips );\n        }\n\n        return $this->pipOrder;\n    }\n\n    public function getOrder()\n    {\n\n        if( !isset( $this->order ) )\n        {\n            $suitOrder = $this->getSuitOrder();\n            $pipOrder = $this->getPipOrder();\n\n            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;\n        }\n\n        return $this->order;\n    }\n\n    public function compareSuit( Card $other )\n    {\n        return $this->getSuitOrder() - $other->getSuitOrder();\n    }\n\n    public function comparePip( Card $other )\n    {\n        return $this->getPipOrder() - $other->getPipOrder();\n    }\n\n    public function compare( Card $other )\n    {\n        return $this->getOrder() - $other->getOrder();\n    }\n\n    public function __toString()\n    {\n        return $this->suit . $this->pip;\n    }\n\n    public static function getSuits()\n    {\n        return self::$suits;\n    }\n\n    public static function getPips()\n    {\n        return self::$pips;\n    }\n}\n\nclass CardCollection\n    implements Countable, Iterator\n{\n    protected $cards = array();\n\n    protected function __construct( array $cards = array() )\n    {\n        foreach( $cards as $card )\n        {\n            $this->addCard( $card );\n        }\n    }\n\n    \n    public function count()\n    {\n        return count( $this->cards );\n    }\n\n    \n    public function key()\n    {\n        return key( $this->cards );\n    }\n\n    \n    public function valid()\n    {\n        return null !== $this->key();\n    }\n\n    \n    public function next()\n    {\n        next( $this->cards );\n    }\n\n    \n    public function current()\n    {\n        return current( $this->cards );\n    }\n\n    \n    public function rewind()\n    {\n        reset( $this->cards );\n    }\n\n    public function sort( $comparer = null )\n    {\n        $comparer = $comparer ?: function( $a, $b ) {\n            return $a->compare( $b );\n        };\n\n        if( !is_callable( $comparer ) )\n        {\n            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );\n        }\n\n        usort( $this->cards, $comparer );\n        return $this;\n    }\n\n    public function toString()\n    {\n        return implode( ' ', $this->cards );\n    }\n\n    public function __toString()\n    {\n        return $this->toString();\n    }\n\n    protected function addCard( Card $card )\n    {\n        if( in_array( $card, $this->cards ) )\n        {\n            throw new DomainException( 'Card is already present in this collection' );\n        }\n\n        $this->cards[] = $card;\n    }\n}\n\nclass Deck\n    extends CardCollection\n{\n    public function __construct( $shuffled = false )\n    {\n        foreach( Card::getSuits() as $suit )\n        {\n            foreach( Card::getPips() as $pip )\n            {\n                $this->addCard( new Card( $suit, $pip ) );\n            }\n        }\n\n        if( $shuffled )\n        {\n            $this->shuffle();\n        }\n    }\n\n    public function deal( $amount = 1, CardCollection $cardCollection = null )\n    {\n        if( !is_int( $amount ) || $amount < 1 )\n        {\n            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );\n        }\n\n        if( $amount > count( $this->cards ) )\n        {\n            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );\n        }\n\n        $cards = array_splice( $this->cards, 0, $amount );\n\n        $cardCollection = $cardCollection ?: new CardCollection;\n\n        foreach( $cards as $card )\n        {\n            $cardCollection->addCard( $card );\n        }\n\n        return $cardCollection;\n    }\n\n    public function shuffle()\n    {\n        shuffle( $this->cards );\n    }\n}\n\nclass Hand\n    extends CardCollection\n{\n\n\n\n    public function __construct() {}\n\n    public function play( $position )\n    {\n        if( !isset( $this->cards[ $position ] ) )\n        {\n            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );\n        }\n\n        $result = array_splice( $this->cards, $position, 1 );\n        return $result[ 0 ];\n    }\n}\n"}
{"id": 44996, "name": "Arrays", "VB": "Option Base {0|1}\n", "PHP": "$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n"}
{"id": 44997, "name": "Sierpinski carpet", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "PHP": "<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x /= 3;\n        $y /= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n"}
{"id": 44998, "name": "Sorting algorithms_Bogosort", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n", "PHP": "function bogosort($l) {\n    while (!in_order($l))\n        shuffle($l);\n    return $l;\n}\n\nfunction in_order($l) {\n    for ($i = 1; $i < count($l); $i++)\n        if ($l[$i] < $l[$i-1])\n            return FALSE;\n    return TRUE;\n}\n"}
{"id": 44999, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "PHP": "<?php\n\n\tfor($i=1;$i<=22;$i++){\n\t\techo($i + floor(1/2 + sqrt($i)) . \"\\n\");\n\t}\n\n\t$found_square=False;\n\tfor($i=1;$i<=1000000;$i++){\n\t\t$non_square=$i + floor(1/2 + sqrt($i));\n\t\tif(sqrt($non_square)==intval(sqrt($non_square))){\n\t\t\t$found_square=True;\n\t\t}\n\t}\n\techo(\"\\n\");\n\tif($found_square){\n\t\techo(\"Found a square number, so the formula does not always work.\");\n\t} else {\n\t\techo(\"Up to 1000000, found no square number in the sequence!\");\n\t}\n?>\n"}
{"id": 45000, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "PHP": "<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; //cde\necho substr($str, $n), \"\\n\"; //cdefgh\necho substr($str, 0, -1), \"\\n\"; //abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; //def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; //def\n?>\n"}
{"id": 45001, "name": "Leap year", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n", "PHP": "<?php\nfunction isLeapYear($year) {\n    if ($year % 100 == 0) {\n        return ($year % 400 == 0);\n    }\n    return ($year % 4 == 0);\n}\n"}
{"id": 45002, "name": "Number names", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n", "PHP": "$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');\n$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',\n'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');\n$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');\n\nfunction NumberToEnglish($num, $count = 0){\n   global $orderOfMag, $smallNumbers, $decades;\n   $isLast = true;\n   $str = '';\n\n   if ($num < 0){\n      $str = 'Negative ';\n      $num = abs($num);\n   }\n\n   (int) $thisPart = substr((string) $num, -3);\n\n   if (strlen((string) $num) > 3){\n\n      $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);\n      $isLast = false;\n   }\n\n   if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))\n\n      $and = '';\n   else\n      $and = ' and ';\n\n   if ($thisPart > 99){\n\n      $str .= ($isLast ? '' : ' ') . \"{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}\";\n\n      if(($thisPart %= 100) == 0){\n\n         $str .= \" {$orderOfMag[$count]}\";\n         return $str;\n      }\n      $and = ' and ';  // Set up our and string to the word \"and\" since there is something in the hundreds place of this chunk\n   }\n\n   if ($thisPart >= 20){\n\n      $str .= \"{$and}{$decades[$thisPart /10]}\";\n      $and = ' '; // Make sure we don't have any extranious \"and\"s\n      if(($thisPart %= 10) == 0)\n         return $str . ($count != 0 ? \" {$orderOfMag[$count]}\" : '');\n   }\n\n   if ($thisPart < 20 && $thisPart > 0)\n\n      return $str . \"{$and}{$smallNumbers[(int) $thisPart]} \" . ($count != 0 ? $orderOfMag[$count] : '');\n   elseif ($thisPart == 0 && strlen($thisPart) == 1)\n\n      return $str . \"{$smallNumbers[(int)$thisPart]}\";\n}\n"}
{"id": 45003, "name": "Sorting algorithms_Shell sort", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n", "PHP": "function shellSort($arr)\n{\n\t$inc = round(count($arr)/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc/2.2);\n\t}\n\treturn $arr;\n}\n"}
{"id": 45004, "name": "Letter frequency", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n", "PHP": "<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n"}
{"id": 45005, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "PHP": "$s = \"12345\";\n$s++;\n"}
{"id": 45006, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "PHP": "<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n"}
{"id": 45007, "name": "Averages_Arithmetic mean", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n", "PHP": "$nums = array(3, 1, 4, 1, 5, 9);\nif ($nums)\n    echo array_sum($nums) / count($nums), \"\\n\";\nelse\n    echo \"0\\n\";\n"}
{"id": 45008, "name": "Forward difference", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n", "PHP": "<?php\n\nfunction forwardDiff($anArray, $times = 1) {\n  if ($times <= 0) { return $anArray; }\n  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { \n    $accumilation[] = $anArray[$i] - $anArray[$i - 1];\n  }\n  if ($times === 1) { return $accumilation; }\n  return forwardDiff($accumilation, $times - 1);\n}\n\nclass ForwardDiffExample extends PweExample {\n  \n  function _should_run_empty_array_for_single_elem() {\n    $expected = array($this->rand()->int());\n    $this->spec(forwardDiff($expected))->shouldEqual(array());\n  }\n  \n  function _should_give_diff_of_two_elem_as_single_elem() {\n    $twoNums = array($this->rand()->int(), $this->rand()->int());\n    $expected = array($twoNums[1] - $twoNums[0]);\n    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);\n  }\n  \n  function _should_compute_correct_forward_diff_for_longer_arrays() {\n    $diffInput = array(10, 2, 9, 6, 5);\n    $expected  = array(-8, 7, -3, -1);\n    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);\n  }\n  \n  function _should_apply_more_than_once_if_specified() {\n    $diffInput = array(4, 6, 9, 3, 4);\n    $expectedAfter1 = array(2, 3, -6, 1);\n    $expectedAfter2 = array(1, -9, 7);\n    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);\n    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);\n  }\n  \n  function _should_return_array_unaltered_if_no_times() {\n    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);\n  }\n  \n}\n"}
{"id": 45009, "name": "Primality by trial division", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n", "PHP": "<?php\nfunction prime($a) {\n  if (($a % 2 == 0 && $a != 2) || $a < 2)\n    return false;\n  $limit = sqrt($a);\n  for ($i = 2; $i <= $limit; $i++)\n    if ($a % $i == 0)\n      return false;\n  return true;\n}\n\nforeach (range(1, 100) as $x)\n  if (prime($x)) echo \"$x\\n\";\n\n?>\n"}
{"id": 45010, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "PHP": "<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n"}
{"id": 45011, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "PHP": "<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n"}
{"id": 45012, "name": "Bitwise operations", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n"}
{"id": 45013, "name": "Dragon curve", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n"}
{"id": 45014, "name": "Read a file line by line", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n", "C#": "foreach (string readLine in File.ReadLines(\"FileName\"))\n  DoSomething(readLine);\n"}
{"id": 45015, "name": "Doubly-linked list_Element insertion", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n"}
{"id": 45016, "name": "Quickselect algorithm", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 45017, "name": "Non-decimal radices_Convert", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 45018, "name": "Walk a directory_Recursively", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 45019, "name": "CRC-32", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 45020, "name": "Classes", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n"}
{"id": 45021, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 45022, "name": "Kaprekar numbers", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 45023, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 45024, "name": "Hofstadter Figure-Figure sequences", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 45025, "name": "Anonymous recursion", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n"}
{"id": 45026, "name": "Create a file", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n"}
{"id": 45027, "name": "Delegates", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 45028, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 45029, "name": "Bacon cipher", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 45030, "name": "Spiral matrix", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n"}
{"id": 45031, "name": "Faulhaber's triangle", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 45032, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 45033, "name": "Command-line arguments", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 45034, "name": "Array concatenation", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 45035, "name": "User input_Text", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n"}
{"id": 45036, "name": "Knapsack problem_0-1", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 45037, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 45038, "name": "Cartesian product of two or more lists", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 45039, "name": "First-class functions", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n"}
{"id": 45040, "name": "Proper divisors", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 45041, "name": "XML_Output", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n"}
{"id": 45042, "name": "Regular expressions", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n"}
{"id": 45043, "name": "Guess the number_With feedback (player)", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n"}
{"id": 45044, "name": "Hash from two arrays", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n"}
{"id": 45045, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 45046, "name": "Bin given limits", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 45047, "name": "Animate a pendulum", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n"}
{"id": 45048, "name": "Sorting algorithms_Heapsort", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n"}
{"id": 45049, "name": "Playing cards", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 45050, "name": "Arrays", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n", "C#": " int[] numbers = new int[10];\n"}
{"id": 45051, "name": "Sierpinski carpet", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n"}
{"id": 45052, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 45053, "name": "Sorting algorithms_Bogosort", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 45054, "name": "Euler method", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 45055, "name": "Sequence of non-squares", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 45056, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 45057, "name": "Substring", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 45058, "name": "JortSort", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n"}
{"id": 45059, "name": "Leap year", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n"}
{"id": 45060, "name": "Sort numbers lexicographically", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n"}
{"id": 45061, "name": "Number names", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n"}
{"id": 45062, "name": "Compare length of two strings", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n"}
{"id": 45063, "name": "Letter frequency", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 45064, "name": "Increment a numerical string", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 45065, "name": "Strip a set of characters from a string", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 45066, "name": "Averages_Arithmetic mean", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n"}
{"id": 45067, "name": "Entropy", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n"}
{"id": 45068, "name": "Tokenize a string with escaping", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n"}
{"id": 45069, "name": "Hello world_Text", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 45070, "name": "Forward difference", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 45071, "name": "Primality by trial division", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 45072, "name": "Evaluate binomial coefficients", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 45073, "name": "Collections", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 45074, "name": "Singly-linked list_Traversal", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n"}
{"id": 45075, "name": "Bitmap_Write a PPM file", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 45076, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n"}
{"id": 45077, "name": "Delete a file", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n"}
{"id": 45078, "name": "Discordian date", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n"}
{"id": 45079, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 45080, "name": "Average loop length", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 45081, "name": "String interpolation (included)", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n"}
{"id": 45082, "name": "Partition function P", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 45083, "name": "Numbers with prime digits whose sum is 13", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 45084, "name": "Numbers with prime digits whose sum is 13", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 45085, "name": "Take notes on the command line", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n"}
{"id": 45086, "name": "Take notes on the command line", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n"}
{"id": 45087, "name": "Angles (geometric), normalization and conversion", "Java": "import java.text.DecimalFormat;\n\n\n\npublic class AnglesNormalizationAndConversion {\n\n    public static void main(String[] args) {\n        DecimalFormat formatAngle = new DecimalFormat(\"######0.000000\");\n        DecimalFormat formatConv = new DecimalFormat(\"###0.0000\");\n        System.out.printf(\"                               degrees    gradiens        mils     radians%n\");\n        for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {\n            for ( String units : new String[] {\"degrees\", \"gradiens\", \"mils\", \"radians\"}) {\n                double d = 0, g = 0, m = 0, r = 0;\n                switch (units) {\n                case \"degrees\":\n                    d = d2d(angle);\n                    g = d2g(d);\n                    m = d2m(d);\n                    r = d2r(d);\n                    break;\n                case \"gradiens\":\n                    g = g2g(angle);\n                    d = g2d(g);\n                    m = g2m(g);\n                    r = g2r(g);\n                    break;\n                case \"mils\":\n                    m = m2m(angle);\n                    d = m2d(m);\n                    g = m2g(m);\n                    r = m2r(m);\n                    break;\n                case \"radians\":\n                    r = r2r(angle);\n                    d = r2d(r);\n                    g = r2g(r);\n                    m = r2m(r);\n                    break;\n                }\n                System.out.printf(\"%15s  %8s = %10s  %10s  %10s  %10s%n\", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));\n            }\n        }\n    }\n\n    private static final double DEGREE = 360D;\n    private static final double GRADIAN = 400D;\n    private static final double MIL = 6400D;\n    private static final double RADIAN = (2 * Math.PI);\n    \n    private static double d2d(double a) {\n        return a % DEGREE;\n    }\n    private static double d2g(double a) {\n        return a * (GRADIAN / DEGREE);\n    }\n    private static double d2m(double a) {\n        return a * (MIL / DEGREE);\n    }\n    private static double d2r(double a) {\n        return a * (RADIAN / 360);\n    }\n\n    private static double g2d(double a) {\n        return a * (DEGREE / GRADIAN);\n    }\n    private static double g2g(double a) {\n        return a % GRADIAN;\n    }\n    private static double g2m(double a) {\n        return a * (MIL / GRADIAN);\n    }\n    private static double g2r(double a) {\n        return a * (RADIAN / GRADIAN);\n    }\n    \n    private static double m2d(double a) {\n        return a * (DEGREE / MIL);\n    }\n    private static double m2g(double a) {\n        return a * (GRADIAN / MIL);\n    }\n    private static double m2m(double a) {\n        return a % MIL;\n    }\n    private static double m2r(double a) {\n        return a * (RADIAN / MIL);\n    }\n    \n    private static double r2d(double a) {\n        return a * (DEGREE / RADIAN);\n    }\n    private static double r2g(double a) {\n        return a * (GRADIAN / RADIAN);\n    }\n    private static double r2m(double a) {\n        return a * (MIL / RADIAN);\n    }\n    private static double r2r(double a) {\n        return a % RADIAN;\n    }\n    \n}\n", "C#": "using System;\n\npublic static class Angles\n{\n    public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);\n\n    public static void Print(params double[] angles) {\n        string[] names = { \"Degrees\", \"Gradians\", \"Mils\", \"Radians\" };\n        Func<double, double> rnd = a => Math.Round(a, 4);\n        Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };\n\n        Func<double, double>[,] convert = {\n            { a => a, DegToGrad, DegToMil, DegToRad },\n            { GradToDeg, a => a, GradToMil, GradToRad },\n            { MilToDeg, MilToGrad, a => a, MilToRad },\n            { RadToDeg, RadToGrad, RadToMil, a => a }\n        };\n\n        Console.WriteLine($@\"{\"Angle\",-12}{\"Normalized\",-12}{\"Unit\",-12}{\n            \"Degrees\",-12}{\"Gradians\",-12}{\"Mils\",-12}{\"Radians\",-12}\");\n\n        foreach (double angle in angles) {\n            for (int i = 0; i < 4; i++) {\n                double nAngle = normal[i](angle);\n\n                Console.WriteLine($@\"{\n                    rnd(angle),-12}{\n                    rnd(nAngle),-12}{\n                    names[i],-12}{\n                    rnd(convert[i, 0](nAngle)),-12}{\n                    rnd(convert[i, 1](nAngle)),-12}{\n                    rnd(convert[i, 2](nAngle)),-12}{\n                    rnd(convert[i, 3](nAngle)),-12}\");\n            }\n        }\n    }\n\n    public static double NormalizeDeg(double angle) => Normalize(angle, 360);\n    public static double NormalizeGrad(double angle) => Normalize(angle, 400);\n    public static double NormalizeMil(double angle) => Normalize(angle, 6400);\n    public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);\n\n    private static double Normalize(double angle, double N) {\n        while (angle <= -N) angle += N;\n        while (angle >= N) angle -= N;\n        return angle;\n    }\n\n    public static double DegToGrad(double angle) => angle * 10 / 9;\n    public static double DegToMil(double angle) => angle * 160 / 9;\n    public static double DegToRad(double angle) => angle * Math.PI / 180;\n    \n    public static double GradToDeg(double angle) => angle * 9 / 10;\n    public static double GradToMil(double angle) => angle * 16;\n    public static double GradToRad(double angle) => angle * Math.PI / 200;\n    \n    public static double MilToDeg(double angle) => angle * 9 / 160;\n    public static double MilToGrad(double angle) => angle / 16;\n    public static double MilToRad(double angle) => angle * Math.PI / 3200;\n    \n    public static double RadToDeg(double angle) => angle * 180 / Math.PI;\n    public static double RadToGrad(double angle) => angle * 200 / Math.PI;\n    public static double RadToMil(double angle) => angle * 3200 / Math.PI;\n}\n"}
{"id": 45088, "name": "Find common directory path", "Java": "public class CommonPath {\n\tpublic static String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\tfor(int i = 0; i < paths.length; i++){\n\t\t\tfolders[i] = paths[i].split(\"/\"); \n\t\t}\n\t\tfor(int j = 0; j < folders[0].length; j++){\n\t\t\tString thisFolder = folders[0][j]; \n\t\t\tboolean allMatched = true; \n\t\t\tfor(int i = 1; i < folders.length && allMatched; i++){ \n\t\t\t\tif(folders[i].length < j){ \n\t\t\t\t\tallMatched = false; \n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tallMatched &= folders[i][j].equals(thisFolder); \n\t\t\t}\n\t\t\tif(allMatched){ \n\t\t\t\tcommonPath += thisFolder + \"/\"; \n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn commonPath;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString[] paths = { \"/home/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths));\n\t\t\n\t\tString[] paths2 = { \"/hame/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths2));\n\t}\n}\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n"}
{"id": 45089, "name": "Recaman's sequence", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 45090, "name": "Recaman's sequence", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 45091, "name": "Memory allocation", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n", "C#": "using System;\nusing System.Runtime.InteropServices;\n\npublic unsafe class Program\n{\n    public static unsafe void HeapMemory()\n    {\n        const int HEAP_ZERO_MEMORY = 0x00000008;\n        const int size = 1000;\n        int ph = GetProcessHeap();\n        void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);\n        if (pointer == null)\n            throw new OutOfMemoryException();\n        Console.WriteLine(HeapSize(ph, 0, pointer));\n        HeapFree(ph, 0, pointer);\n    }\n\n    public static unsafe void StackMemory()\n    {\n        byte* buffer = stackalloc byte[1000];\n        \n    }\n    public static void Main(string[] args)\n    {\n        HeapMemory();\n        StackMemory();\n    }\n    [DllImport(\"kernel32\")]\n    static extern void* HeapAlloc(int hHeap, int flags, int size);\n    [DllImport(\"kernel32\")]\n    static extern bool HeapFree(int hHeap, int flags, void* block);\n    [DllImport(\"kernel32\")]\n    static extern int GetProcessHeap();\n    [DllImport(\"kernel32\")]\n    static extern int HeapSize(int hHeap, int flags, void* block);\n\n}\n"}
{"id": 45092, "name": "Integer sequence", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n"}
{"id": 45093, "name": "Integer sequence", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n"}
{"id": 45094, "name": "DNS query", "Java": "import java.net.InetAddress;\nimport java.net.Inet4Address;\nimport java.net.Inet6Address;\nimport java.net.UnknownHostException;\n\nclass DnsQuery {\n    public static void main(String[] args) {\n        try {\n            InetAddress[] ipAddr = InetAddress.getAllByName(\"www.kame.net\");\n            for(int i=0; i < ipAddr.length ; i++) {\n                if (ipAddr[i] instanceof Inet4Address) {\n                    System.out.println(\"IPv4 : \" + ipAddr[i].getHostAddress());\n                } else if (ipAddr[i] instanceof Inet6Address) {\n                    System.out.println(\"IPv6 : \" + ipAddr[i].getHostAddress());\n                }\n            }\n        } catch (UnknownHostException uhe) {\n            System.err.println(\"unknown host\");\n        }\n    }\n}\n", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n"}
{"id": 45095, "name": "Seven-sided dice from five-sided dice", "Java": "import java.util.Random;\npublic class SevenSidedDice \n{\n\tprivate static final Random rnd = new Random();\n\tpublic static void main(String[] args)\n\t{\n\t\tSevenSidedDice now=new SevenSidedDice();\n\t\tSystem.out.println(\"Random number from 1 to 7: \"+now.seven());\n\t}\n\tint seven()\n\t{\n\t\tint v=21;\n\t\twhile(v>20)\n\t\t\tv=five()+five()*5-6;\n\t\treturn 1+v%7;\n\t}\n\tint five()\n\t{\n\t\treturn 1+rnd.nextInt(5);\n\t}\n}\n", "C#": "using System;\n\npublic class SevenSidedDice\n{\n    Random random = new Random();\n\t\t\n        static void Main(string[] args)\n\t\t{\n\t\t\tSevenSidedDice sevenDice = new SevenSidedDice();\n\t\t\tConsole.WriteLine(\"Random number from 1 to 7: \"+ sevenDice.seven());\n            Console.Read();\n\t\t}\n\t\t\n\t\tint seven()\n\t\t{\n\t\t\tint v=21;\n\t\t\twhile(v>20)\n\t\t\t\tv=five()+five()*5-6;\n\t\t\treturn 1+v%7;\n\t\t}\n\t\t\n\t\tint five()\n\t\t{\n        return 1 + random.Next(5);\n\t\t}\n}\n"}
{"id": 45096, "name": "Magnanimous numbers", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class MagnanimousNumbers {\n\n    public static void main(String[] args) {\n        runTask(\"Find and display the first 45 magnanimous numbers.\", 1, 45);\n        runTask(\"241st through 250th magnanimous numbers.\", 241, 250);\n        runTask(\"391st through 400th magnanimous numbers.\", 391, 400);\n    }\n    \n    private static void runTask(String message, int startN, int endN) {\n        int count = 0;\n        List<Integer> nums = new ArrayList<>();\n        for ( int n = 0 ; count < endN ; n++ ) {\n            if ( isMagnanimous(n) ) {\n                nums.add(n);\n                count++;\n            }\n        }\n        System.out.printf(\"%s%n\", message);\n        System.out.printf(\"%s%n%n\", nums.subList(startN-1, endN));\n    }\n    \n    private static boolean isMagnanimous(long n) {\n        if ( n >= 0 && n <= 9 ) {\n            return true;\n        }\n        long q = 11;\n        for ( long div = 10 ; q >= 10 ; div *= 10 ) {\n            q = n / div;\n            long r = n % div;\n            if ( ! isPrime(q+r) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n", "C#": "using System; using static System.Console;\n\nclass Program {\n\n  static bool[] np; \n\n  static void ms(long lmt) { \n    np = new bool[lmt]; np[0] = np[1] = true;\n    for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])\n        for (long k = n * n; k < lmt; k += n) np[k] = true; }\n\n  static bool is_Mag(long n) { long res, rem;\n    for (long p = 10; n >= p; p *= 10) {\n      res = Math.DivRem (n, p, out rem);\n      if (np[res + rem]) return false; } return true; }\n\n  static void Main(string[] args) { ms(100_009); string mn;\n    WriteLine(\"First 45{0}\", mn = \" magnanimous numbers:\");\n    for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {\n      if (c++ < 45 || (c > 240 && c <= 250) || c > 390)\n        Write(c <= 45 ? \"{0,4} \" : \"{0,8:n0} \", l);\n      if (c < 45 && c % 15 == 0) WriteLine();\n      if (c == 240) WriteLine (\"\\n\\n241st through 250th{0}\", mn);\n      if (c == 390) WriteLine (\"\\n\\n391st through 400th{0}\", mn); } }\n}\n"}
{"id": 45097, "name": "Create a two-dimensional array at runtime", "Java": "import java.util.Scanner;\n\npublic class twoDimArray {\n  public static void main(String[] args) {\n        Scanner in = new Scanner(System.in);\n        \n        int nbr1 = in.nextInt();\n        int nbr2 = in.nextInt();\n        \n        double[][] array = new double[nbr1][nbr2];\n        array[0][0] = 42.0;\n        System.out.println(\"The number at place [0 0] is \" + array[0][0]);\n  }\n}\n", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 45098, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 45099, "name": "Dragon curve", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n"}
{"id": 45100, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 45101, "name": "Doubly-linked list_Element insertion", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 45102, "name": "Smarandache prime-digital sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n", "Java": "public class SmarandachePrimeDigitalSequence {\n\n    public static void main(String[] args) {\n        long s = getNextSmarandache(7);\n        System.out.printf(\"First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 \");\n        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                System.out.printf(\"%d \", s);\n                count++;\n            }\n        }\n        System.out.printf(\"%n%n\");\n        for (int i = 2 ; i <=5 ; i++ ) {\n            long n = (long) Math.pow(10, i);\n            System.out.printf(\"%,dth Smarandache prime-digital sequence number = %d%n\", n, getSmarandachePrime(n));\n        }\n    }\n    \n    private static final long getSmarandachePrime(long n) {\n        if ( n < 10 ) {\n            switch ((int) n) {\n            case 1:  return 2;\n            case 2:  return 3;\n            case 3:  return 5;\n            case 4:  return 7;\n            }\n        }\n        long s = getNextSmarandache(7);\n        long result = 0;\n        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {\n            if ( isPrime(s) ) {\n                count++;\n                result = s;\n            }\n        }\n        return result;\n    }\n    \n    private static final boolean isPrime(long test) {\n        if ( test % 2 == 0 ) return false;\n        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {\n            if ( test % i == 0 ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static long getNextSmarandache(long n) {\n        \n        if ( n % 10 == 3 ) {\n            return n+4;\n        }\n        long retVal = n-4;\n        \n        \n        int k = 0;\n        while ( n % 10 == 7 ) {\n            k++;\n            n /= 10;\n        }\n        \n        \n        long digit = n % 10;\n\n        \n        long coeff = (digit == 2 ? 1 : 2);\n        \n        \n        retVal += coeff * Math.pow(10, k);\n        \n        \n        while ( k > 1 ) {\n            retVal -= 5 * Math.pow(10, k-1);\n            k--;\n        }\n        \n        \n        return retVal;\n    }\n\n}\n"}
{"id": 45103, "name": "Quickselect algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 45104, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 45105, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 45106, "name": "State name puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n", "Java": "import java.util.*;\nimport java.util.stream.*;\n\npublic class StateNamePuzzle {\n\n    static String[] states = {\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n        \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \"Florida\",\n        \"Georgia\", \"hawaii\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n        \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\",\n        \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n        \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n        \"New York\", \"North Carolina \", \"North Dakota\", \"Ohio\", \"Oklahoma\",\n        \"Oregon\", \"Pennsylvania\", \"Rhode Island\", \"South Carolina\",\n        \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\", \"Vermont\", \"Virginia\",\n        \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",};\n\n    public static void main(String[] args) {\n        solve(Arrays.asList(states));\n    }\n\n    static void solve(List<String> input) {\n        Map<String, String> orig = input.stream().collect(Collectors.toMap(\n                s -> s.replaceAll(\"\\\\s\", \"\").toLowerCase(), s -> s, (s, a) -> s));\n\n        input = new ArrayList<>(orig.keySet());\n\n        Map<String, List<String[]>> map = new HashMap<>();\n        for (int i = 0; i < input.size() - 1; i++) {\n            String pair0 = input.get(i);\n            for (int j = i + 1; j < input.size(); j++) {\n\n                String[] pair = {pair0, input.get(j)};\n                String s = pair0 + pair[1];\n                String key = Arrays.toString(s.chars().sorted().toArray());\n\n                List<String[]> val = map.getOrDefault(key, new ArrayList<>());\n                val.add(pair);\n                map.put(key, val);\n            }\n        }\n\n        map.forEach((key, list) -> {\n            for (int i = 0; i < list.size() - 1; i++) {\n                String[] a = list.get(i);\n                for (int j = i + 1; j < list.size(); j++) {\n                    String[] b = list.get(j);\n\n                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)\n                        continue;\n\n                    System.out.printf(\"%s + %s = %s + %s %n\", orig.get(a[0]),\n                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));\n                }\n            }\n        });\n    }\n}\n"}
{"id": 45107, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 45108, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 45109, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 45110, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 45111, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 45112, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 45113, "name": "LZW compression", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n"}
{"id": 45114, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 45115, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 45116, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 45117, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 45118, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 45119, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 45120, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n    public static void main(String[] args) {\n         System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n    }\n\n    private static List<Integer> yellowstoneSequence(int sequenceCount) {\n        List<Integer> yellowstoneList = new ArrayList<Integer>();\n        yellowstoneList.add(1);\n        yellowstoneList.add(2);\n        yellowstoneList.add(3);\n        int num = 4;\n        List<Integer> notYellowstoneList = new ArrayList<Integer>();\n        int yellowSize = 3;\n        while ( yellowSize < sequenceCount ) {\n            int found = -1;\n            for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n                int test = notYellowstoneList.get(index);\n                if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n                    found = index;\n                    break;\n                }\n            }\n            if ( found >= 0 ) {\n                yellowstoneList.add(notYellowstoneList.remove(found));\n                yellowSize++;\n            }\n            else {\n                while ( true ) {\n                    if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n                        yellowstoneList.add(num);\n                        yellowSize++;\n                        num++;\n                        break;\n                    }\n                    notYellowstoneList.add(num);\n                    num++;\n                }\n            }\n        }\n        return yellowstoneList;\n    }\n        \n    private static final int gcd(int a, int b) {\n        if ( b == 0 ) {\n            return a;\n        }\n        return gcd(b, a%b);\n    }\n\n}\n"}
{"id": 45121, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 45122, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "Java": "import java.util.*;\n\npublic class CutRectangle {\n\n    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n    public static void main(String[] args) {\n        cutRectangle(2, 2);\n        cutRectangle(4, 3);\n    }\n\n    static void cutRectangle(int w, int h) {\n        if (w % 2 == 1 && h % 2 == 1)\n            return;\n\n        int[][] grid = new int[h][w];\n        Stack<Integer> stack = new Stack<>();\n\n        int half = (w * h) / 2;\n        long bits = (long) Math.pow(2, half) - 1;\n\n        for (; bits > 0; bits -= 2) {\n\n            for (int i = 0; i < half; i++) {\n                int r = i / w;\n                int c = i % w;\n                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n            }\n\n            stack.push(0);\n            grid[0][0] = 2;\n            int count = 1;\n            while (!stack.empty()) {\n\n                int pos = stack.pop();\n                int r = pos / w;\n                int c = pos % w;\n\n                for (int[] dir : dirs) {\n\n                    int nextR = r + dir[0];\n                    int nextC = c + dir[1];\n\n                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n                        if (grid[nextR][nextC] == 1) {\n                            stack.push(nextR * w + nextC);\n                            grid[nextR][nextC] = 2;\n                            count++;\n                        }\n                    }\n                }\n            }\n            if (count == half) {\n                printResult(grid);\n            }\n        }\n    }\n\n    static void printResult(int[][] arr) {\n        for (int[] a : arr)\n            System.out.println(Arrays.toString(a));\n        System.out.println();\n    }\n}\n"}
{"id": 45123, "name": "Mertens function", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n", "Java": "public class MertensFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the merten function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", mertenFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n        \n        for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {\n            int zeroCount = 0;\n            int zeroCrossingCount = 0;\n            int positiveCount = 0;\n            int negativeCount = 0;\n            int mSum = 0;\n            int mMin = Integer.MAX_VALUE;\n            int mMinIndex = 0;\n            int mMax = Integer.MIN_VALUE;\n            int mMaxIndex = 0;\n            int nMax = (int) Math.pow(10, exponent);\n            for ( int n = 1 ; n <= nMax ; n++ ) {\n                int m = mertenFunction(n);\n                mSum += m;\n                if ( m < mMin ) {\n                    mMin = m;\n                    mMinIndex = n;\n                }\n                if ( m > mMax ) {\n                    mMax = m;\n                    mMaxIndex = n;\n                }\n                if ( m > 0 ) {\n                    positiveCount++;\n                }\n                if ( m < 0 ) {\n                    negativeCount++;\n                }\n                if ( m == 0 ) {\n                    zeroCount++;\n                }\n                if ( m == 0 && mertenFunction(n - 1) != 0 ) {\n                    zeroCrossingCount++;\n                }\n            }\n            System.out.printf(\"%nFor M(x) with x from 1 to %,d%n\", nMax);        \n            System.out.printf(\"The maximum of M(x) is M(%,d) = %,d.%n\", mMaxIndex, mMax);\n            System.out.printf(\"The minimum of M(x) is M(%,d) = %,d.%n\", mMinIndex, mMin);\n            System.out.printf(\"The sum of M(x) is %,d.%n\", mSum);\n            System.out.printf(\"The count of positive M(x) is %,d, count of negative M(x) is %,d.%n\", positiveCount, negativeCount);\n            System.out.printf(\"M(x) has %,d zeroes in the interval.%n\", zeroCount);\n            System.out.printf(\"M(x) has %,d crossings in the interval.%n\", zeroCrossingCount);\n        }\n    }\n    \n    private static int MU_MAX = 100_000_000;\n    private static int[] MU = null;\n    private static int[] MERTEN = null;\n        \n    \n    private static int mertenFunction(int n) {\n        if ( MERTEN != null ) {\n            return MERTEN[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        MERTEN = new int[MU_MAX+1];\n        MERTEN[1] = 1;\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        int sum = 1;\n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n            sum += MU[i];\n            MERTEN[i] = sum;\n        }\n        return MERTEN[n];\n    }\n\n}\n"}
{"id": 45124, "name": "Order by pair comparisons", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n", "Java": "import java.util.*;\n\npublic class SortComp1 {\n    public static void main(String[] args) {\n        List<String> items = Arrays.asList(\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\");\n        List<String> sortedItems = new ArrayList<>();\n        Comparator<String> interactiveCompare = new Comparator<String>() {\n                int count = 0;\n                Scanner s = new Scanner(System.in);\n                public int compare(String s1, String s2) {\n                    System.out.printf(\"(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: \", ++count, s1, s2);\n                    return s.nextInt();\n                }\n            };\n        for (String item : items) {\n            System.out.printf(\"Inserting '%s' into %s\\n\", item, sortedItems);\n            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);\n            \n            \n            if (spotToInsert < 0) spotToInsert = ~spotToInsert;\n            sortedItems.add(spotToInsert, item);\n        }\n        System.out.println(sortedItems);\n    }\n}\n"}
{"id": 45125, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 45126, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 45127, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 45128, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "Java": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.TimeZone;\n\npublic class NauticalBell extends Thread {\n\n    public static void main(String[] args) {\n        NauticalBell bells = new NauticalBell();\n        bells.setDaemon(true);\n        bells.start();\n        try {\n            bells.join();\n        } catch (InterruptedException e) {\n            System.out.println(e);\n        }\n    }\n\n    @Override\n    public void run() {\n        DateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");\n        sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n        int numBells = 0;\n        long time = System.currentTimeMillis();\n        long next = time - (time % (24 * 60 * 60 * 1000)); \n\n        while (next < time) {\n            next += 30 * 60 * 1000; \n            numBells = 1 + (numBells % 8);\n        }\n\n        while (true) {\n            long wait = 100L;\n            time = System.currentTimeMillis();\n            if (time - next >= 0) {\n                String bells = numBells == 1 ? \"bell\" : \"bells\";\n                String timeString = sdf.format(time);\n                System.out.printf(\"%s : %d %s\\n\", timeString, numBells, bells);\n                next += 30 * 60 * 1000;\n                wait = next - time;\n                numBells = 1 + (numBells % 8);\n            }\n            try {\n                Thread.sleep(wait);\n            } catch (InterruptedException e) {\n                return;\n            }\n        }\n    }\n}\n"}
{"id": 45129, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 45130, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 45131, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 45132, "name": "Legendre prime counting function", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n    public static void main(String[] args) {\n        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n        for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n            System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n    }\n\n    private List<Integer> primes;\n\n    public LegendrePrimeCounter(int limit) {\n        primes = generatePrimes((int)Math.sqrt((double)limit));\n    }\n\n    public int primeCount(int n) {\n        if (n < 2)\n            return 0;\n        int a = primeCount((int)Math.sqrt((double)n));\n        return phi(n, a) + a - 1;\n    }\n\n    private int phi(int x, int a) {\n        if (a == 0)\n            return x;\n        if (a == 1)\n            return x - (x >> 1);\n        int pa = primes.get(a - 1);\n        if (x <= pa)\n            return 1;\n        return phi(x, a - 1) - phi(x / pa, a - 1);\n    }\n\n    private static List<Integer> generatePrimes(int limit) {\n        boolean[] sieve = new boolean[limit >> 1];\n        Arrays.fill(sieve, true);\n        for (int p = 3, s = 9; s < limit; p += 2) {\n            if (sieve[p >> 1]) {\n                for (int q = s; q < limit; q += p << 1)\n                    sieve[q >> 1] = false;\n            }\n            s += (p + 1) << 2;\n        }\n        List<Integer> primes = new ArrayList<>();\n        if (limit > 2)\n            primes.add(2);\n        for (int i = 1; i < sieve.length; ++i) {\n            if (sieve[i])\n                primes.add((i << 1) + 1);\n        } \n        return primes;\n    }\n}\n"}
{"id": 45133, "name": "Use another language to call a function", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n", "Java": "\npublic class Query {\n    public static boolean call(byte[] data, int[] length)\n\tthrows java.io.UnsupportedEncodingException\n    {\n\tString message = \"Here am I\";\n\tbyte[] mb = message.getBytes(\"utf-8\");\n\tif (length[0] < mb.length)\n\t    return false;\n\tlength[0] = mb.length;\n\tSystem.arraycopy(mb, 0, data, 0, mb.length);\n\treturn true;\n    }\n}\n"}
{"id": 45134, "name": "Longest string challenge", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 45135, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n"}
{"id": 45136, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n"}
{"id": 45137, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 45138, "name": "Unprimeable numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n", "Java": "public class UnprimeableNumbers {\n\n    private static int MAX = 10_000_000;\n    private static boolean[] primes = new boolean[MAX];\n\n    public static void main(String[] args) {\n        sieve();\n        System.out.println(\"First 35 unprimeable numbers:\");\n        displayUnprimeableNumbers(35);\n        int n = 600;\n        System.out.printf(\"%nThe %dth unprimeable number = %,d%n%n\", n, nthUnprimeableNumber(n));\n        int[] lowest = genLowest();\n        System.out.println(\"Least unprimeable number that ends in:\");\n        for ( int i = 0 ; i <= 9 ; i++ ) {\n            System.out.printf(\" %d is %,d%n\", i, lowest[i]);\n        }\n    }\n    \n    private static int[] genLowest() {\n        int[] lowest = new int[10];\n        int count = 0;\n        int test = 1;\n        while ( count < 10 ) {\n            test++;\n            if ( unPrimable(test) && lowest[test % 10] == 0 ) {\n                lowest[test % 10] = test;\n                count++;\n            }\n        }\n        return lowest;\n    }\n\n    private static int nthUnprimeableNumber(int maxCount) {\n        int test = 1;\n        int count = 0;\n        int result = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                result = test;\n            }\n        }\n        return result;\n    }\n\n    private static void displayUnprimeableNumbers(int maxCount) {\n        int test = 1;\n        int count = 0;\n        while ( count < maxCount ) {\n            test++;\n            if ( unPrimable(test) ) {\n                count++;\n                System.out.printf(\"%d \", test);\n            }\n        }\n        System.out.println();\n    }\n    \n    private static boolean unPrimable(int test) {\n        if ( primes[test] ) {\n            return false;\n        }\n        String s = test + \"\";\n        for ( int i = 0 ; i < s.length() ; i++ ) {\n            for ( int j = 0 ; j <= 9 ; j++ ) {\n                if ( primes[Integer.parseInt(replace(s, i, j))] ) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    private static String replace(String str, int position, int value) {\n        char[] sChar = str.toCharArray();\n        sChar[position] = (char) value;\n        return str.substring(0, position) + value + str.substring(position + 1);\n    }\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 45139, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 45140, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class PascalsTrianglePuzzle {\n\n    public static void main(String[] args) {\n        Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), \n                                Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),\n                                Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),\n                                Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),\n                                Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));\n        List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);\n        List<Double> solution = cramersRule(mat, b);\n        System.out.println(\"Solution = \" + cramersRule(mat, b));\n        System.out.printf(\"X = %.2f%n\", solution.get(8));\n        System.out.printf(\"Y = %.2f%n\", solution.get(9));\n        System.out.printf(\"Z = %.2f%n\", solution.get(10));\n    }\n    \n    private static List<Double> cramersRule(Matrix matrix, List<Double> b) {\n        double denominator = matrix.determinant();\n        List<Double> result = new ArrayList<>();\n        for ( int i = 0 ; i < b.size() ; i++ ) {\n            result.add(matrix.replaceColumn(b, i).determinant() / denominator);\n        }\n        return result;\n    }\n        \n    private static class Matrix {\n        \n        private List<List<Double>> matrix;\n        \n        @Override\n        public String toString() {\n            return matrix.toString();\n        }\n        \n        @SafeVarargs\n        public Matrix(List<Double> ... lists) {\n            matrix = new ArrayList<>();\n            for ( List<Double> list : lists) {\n                matrix.add(list);\n            }\n        }\n        \n        public Matrix(List<List<Double>> mat) {\n            matrix = mat;\n        }\n        \n        public double determinant() {\n            if ( matrix.size() == 1 ) {\n                return get(0, 0);\n            }\n            if ( matrix.size() == 2 ) {\n                return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);\n            }\n            double sum = 0;\n            double sign = 1;\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                sum += sign * get(0, i) * coFactor(0, i).determinant();\n                sign *= -1;\n            }\n            return sum;\n        }\n        \n        private Matrix coFactor(int row, int col) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int i = 0 ; i < matrix.size() ; i++ ) {\n                if ( i == row ) {\n                    continue;\n                }\n                List<Double> list = new ArrayList<>();\n                for ( int j = 0 ; j < matrix.size() ; j++ ) {\n                    if ( j == col ) {\n                        continue;\n                    }\n                    list.add(get(i, j));\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private Matrix replaceColumn(List<Double> b, int column) {\n            List<List<Double>> mat = new ArrayList<>();\n            for ( int row = 0 ; row < matrix.size() ; row++ ) {\n                List<Double> list = new ArrayList<>();\n                for ( int col = 0 ; col < matrix.size() ; col++ ) {\n                    double value = get(row, col);\n                    if ( col == column ) {\n                        value = b.get(row);\n                    }\n                    list.add(value);\n                }\n                mat.add(list);\n            }\n            return new Matrix(mat);\n        }\n\n        private double get(int row, int col) {\n            return matrix.get(row).get(col);\n        }\n        \n    }\n\n}\n"}
{"id": 45141, "name": "Chernick's Carmichael numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ChernicksCarmichaelNumbers {\n\n    public static void main(String[] args) {\n        for ( long n = 3 ; n < 10 ; n++ ) {\n            long m = 0;\n            boolean foundComposite = true;\n            List<Long> factors = null;\n            while ( foundComposite ) {\n                m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);\n                factors = U(n, m);\n                foundComposite = false;\n                for ( long factor : factors ) {\n                    if ( ! isPrime(factor) ) {\n                        foundComposite = true;\n                        break;\n                    }\n                }\n            }\n            System.out.printf(\"U(%d, %d) = %s = %s %n\", n, m, display(factors), multiply(factors));\n        }\n    }\n    \n    private static String display(List<Long> factors) {\n        return factors.toString().replace(\"[\", \"\").replace(\"]\", \"\").replaceAll(\", \", \" * \");\n    }\n    \n    private static BigInteger multiply(List<Long> factors) {\n        BigInteger result = BigInteger.ONE;\n        for ( long factor : factors ) {\n            result = result.multiply(BigInteger.valueOf(factor));\n        }\n        return result;\n    }\n    \n    private static List<Long> U(long n, long m) {\n        List<Long> factors = new ArrayList<>();\n        factors.add(6*m + 1);\n        factors.add(12*m + 1);\n        for ( int i = 1 ; i <= n-2 ; i++ ) {\n            factors.add(((long)Math.pow(2, i)) * 9 * m + 1);\n        }\n        return factors;\n    }\n\n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n"}
{"id": 45142, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 45143, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 45144, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "Java": "import java.util.Objects;\n\npublic class FindTriangle {\n    private static final double EPS = 0.001;\n    private static final double EPS_SQUARE = EPS * EPS;\n\n    public static class Point {\n        private final double x, y;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n        }\n\n        public double getX() {\n            return x;\n        }\n\n        public double getY() {\n            return y;\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"(%f, %f)\", x, y);\n        }\n    }\n\n    public static class Triangle {\n        private final Point p1, p2, p3;\n\n        public Triangle(Point p1, Point p2, Point p3) {\n            this.p1 = Objects.requireNonNull(p1);\n            this.p2 = Objects.requireNonNull(p2);\n            this.p3 = Objects.requireNonNull(p3);\n        }\n\n        public Point getP1() {\n            return p1;\n        }\n\n        public Point getP2() {\n            return p2;\n        }\n\n        public Point getP3() {\n            return p3;\n        }\n\n        private boolean pointInTriangleBoundingBox(Point p) {\n            var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;\n            var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;\n            var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;\n            var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;\n            return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());\n        }\n\n        private static double side(Point p1, Point p2, Point p) {\n            return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());\n        }\n\n        private boolean nativePointInTriangle(Point p) {\n            boolean checkSide1 = side(p1, p2, p) >= 0;\n            boolean checkSide2 = side(p2, p3, p) >= 0;\n            boolean checkSide3 = side(p3, p1, p) >= 0;\n            return checkSide1 && checkSide2 && checkSide3;\n        }\n\n        private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {\n            double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());\n            double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;\n            if (dotProduct < 0) {\n                return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());\n            }\n            if (dotProduct <= 1) {\n                double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());\n                return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n            }\n            return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());\n        }\n\n        private boolean accuratePointInTriangle(Point p) {\n            if (!pointInTriangleBoundingBox(p)) {\n                return false;\n            }\n            if (nativePointInTriangle(p)) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n                return true;\n            }\n            if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n                return true;\n            }\n            return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;\n        }\n\n        public boolean within(Point p) {\n            Objects.requireNonNull(p);\n            return accuratePointInTriangle(p);\n        }\n\n        @Override\n        public String toString() {\n            return String.format(\"Triangle[%s, %s, %s]\", p1, p2, p3);\n        }\n    }\n\n    private static void test(Triangle t, Point p) {\n        System.out.println(t);\n        System.out.printf(\"Point %s is within triangle? %s\\n\", p, t.within(p));\n    }\n\n    public static void main(String[] args) {\n        var p1 = new Point(1.5, 2.4);\n        var p2 = new Point(5.1, -3.1);\n        var p3 = new Point(-3.8, 1.2);\n        var tri = new Triangle(p1, p2, p3);\n        test(tri, new Point(0, 0));\n        test(tri, new Point(0, 1));\n        test(tri, new Point(3, 1));\n        System.out.println();\n\n        p1 = new Point(1.0 / 10, 1.0 / 9);\n        p2 = new Point(100.0 / 8, 100.0 / 3);\n        p3 = new Point(100.0 / 4, 100.0 / 9);\n        tri = new Triangle(p1, p2, p3);\n        var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));\n        test(tri, pt);\n        System.out.println();\n\n        p3 = new Point(-100.0 / 8, 100.0 / 6);\n        tri = new Triangle(p1, p2, p3);\n        test(tri, pt);\n    }\n}\n"}
{"id": 45145, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 45146, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Java": "public class TauFunction {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final int limit = 100;\n        System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%3d\", divisorCount(n));\n            if (n % 20 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 45147, "name": "Sequence of primorial primes", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n    final static int sieveLimit = 1550_000;\n    static boolean[] notPrime = sieve(sieveLimit);\n\n    public static void main(String[] args) {\n\n        int count = 0;\n        for (int i = 1; i < 1000_000 && count < 20; i++) {\n            BigInteger b = primorial(i);\n            if (b.add(BigInteger.ONE).isProbablePrime(1)\n                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n                System.out.printf(\"%d \", i);\n                count++;\n            }\n        }\n    }\n\n    static BigInteger primorial(int n) {\n        if (n == 0)\n            return BigInteger.ONE;\n\n        BigInteger result = BigInteger.ONE;\n        for (int i = 0; i < sieveLimit && n > 0; i++) {\n            if (notPrime[i])\n                continue;\n            result = result.multiply(BigInteger.valueOf(i));\n            n--;\n        }\n        return result;\n    }\n\n    public static boolean[] sieve(int limit) {\n        boolean[] composite = new boolean[limit];\n        composite[0] = composite[1] = true;\n\n        int max = (int) Math.sqrt(limit);\n        for (int n = 2; n <= max; n++) {\n            if (!composite[n]) {\n                for (int k = n * n; k < limit; k += n) {\n                    composite[k] = true;\n                }\n            }\n        }\n        return composite;\n    }\n}\n"}
{"id": 45148, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 45149, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 45150, "name": "Dining philosophers", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n"}
{"id": 45151, "name": "Dining philosophers", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n"}
{"id": 45152, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 45153, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 45154, "name": "Logistic curve fitting in epidemiology", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n", "Java": "import java.util.List;\nimport java.util.function.Function;\n\npublic class LogisticCurveFitting {\n    private static final double K = 7.8e9;\n    private static final int N0 = 27;\n\n    private static final List<Double> ACTUAL = List.of(\n        27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,\n        61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n        4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,\n        31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,\n        69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n        80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,\n        95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,\n        133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,\n        271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,\n        656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0\n    );\n\n    private static double f(double r) {\n        var sq = 0.0;\n        var len = ACTUAL.size();\n        for (int i = 0; i < len; i++) {\n            var eri = Math.exp(r * i);\n            var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);\n            var diff = guess - ACTUAL.get(i);\n            sq += diff * diff;\n        }\n        return sq;\n    }\n\n    private static double solve(Function<Double, Double> fn) {\n        return solve(fn, 0.5, 0.0);\n    }\n\n    private static double solve(Function<Double, Double> fn, double guess, double epsilon) {\n        double delta;\n        if (guess != 0.0) {\n            delta = guess;\n        } else {\n            delta = 1.0;\n        }\n\n        var f0 = fn.apply(guess);\n        var factor = 2.0;\n\n        while (delta > epsilon && guess != guess - delta) {\n            var nf = fn.apply(guess - delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess -= delta;\n            } else {\n                nf = fn.apply(guess + delta);\n                if (nf < f0) {\n                    f0 = nf;\n                    guess += delta;\n                } else {\n                    factor = 0.5;\n                }\n            }\n\n            delta *= factor;\n        }\n\n        return guess;\n    }\n\n    public static void main(String[] args) {\n        var r = solve(LogisticCurveFitting::f);\n        var r0 = Math.exp(12.0 * r);\n        System.out.printf(\"r = %.16f, R0 = %.16f\\n\", r, r0);\n    }\n}\n"}
{"id": 45155, "name": "Sorting algorithms_Strand sort", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n", "Java": "import java.util.Arrays;\nimport java.util.LinkedList;\n\npublic class Strand{\n\t\n\tpublic static <E extends Comparable<? super E>> \n\tLinkedList<E> strandSort(LinkedList<E> list){\n\t\tif(list.size() <= 1) return list;\n\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(list.size() > 0){\n\t\t\tLinkedList<E> sorted = new LinkedList<E>();\n\t\t\tsorted.add(list.removeFirst()); \n\t\t\tfor(Iterator<E> it = list.iterator(); it.hasNext(); ){\n\t\t\t\tE elem = it.next();\n\t\t\t\tif(sorted.peekLast().compareTo(elem) <= 0){\n\t\t\t\t\tsorted.addLast(elem); \n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = merge(sorted, result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate static <E extends Comparable<? super E>>\n\tLinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){\n\t\tLinkedList<E> result = new LinkedList<E>();\n\t\twhile(!left.isEmpty() && !right.isEmpty()){\n\t\t\t\n\t\t\tif(left.peek().compareTo(right.peek()) <= 0)\n\t\t\t\tresult.add(left.remove());\n\t\t\telse\n\t\t\t\tresult.add(right.remove());\n\t\t}\n\t\tresult.addAll(left);\n\t\tresult.addAll(right);\n\t\treturn result;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));\n\t\tSystem.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));\n\t}\n}\n"}
{"id": 45156, "name": "Additive primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n", "Java": "public class additivePrimes {\n\n    public static void main(String[] args) {\n        int additive_primes = 0;\n        for (int i = 2; i < 500; i++) {\n            if(isPrime(i) && isPrime(digitSum(i))){\n                additive_primes++;\n                System.out.print(i + \" \");\n            }\n        }\n        System.out.print(\"\\nFound \" + additive_primes + \" additive primes less than 500\");\n    }\n\n    static boolean isPrime(int n) {\n        int counter = 1;\n        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {\n            return false;\n        }\n        while (counter * 6 - 1 <= Math.sqrt(n)) {\n            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {\n                return false;\n            } else {\n                counter++;\n            }\n        }\n        return true;\n    }\n\n    static int digitSum(int n) {\n        int sum = 0;\n        while (n > 0) {\n            sum += n % 10;\n            n /= 10;\n        }\n        return sum;\n    }\n}\n"}
{"id": 45157, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 45158, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 45159, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class PerfectTotientNumbers {\n\n    public static void main(String[] args) {\n        computePhi();\n        int n = 20;\n        System.out.printf(\"The first %d perfect totient numbers:%n%s%n\", n, perfectTotient(n));\n    }\n    \n    private static final List<Integer> perfectTotient(int n) {\n        int test = 2;\n        List<Integer> results = new ArrayList<Integer>();\n        for ( int i = 0 ; i < n ; test++ ) {\n            int phiLoop = test;\n            int sum = 0;\n            do {\n                phiLoop = phi[phiLoop];\n                sum += phiLoop;\n            } while ( phiLoop > 1);\n            if ( sum == test ) {\n                i++;\n                results.add(test);\n            }\n        }\n        return results;\n    }\n\n    private static final int max = 100000;\n    private static final int[] phi = new int[max+1];\n\n    private static final void computePhi() {\n        for ( int i = 1 ; i <= max ; i++ ) {\n            phi[i] = i;\n        }\n        for ( int i = 2 ; i <= max ; i++ ) {\n            if (phi[i] < i) continue;\n            for ( int j = i ; j <= max ; j += i ) {\n                phi[j] -= phi[j] / i;\n            }\n        }\n    }\n\n}\n"}
{"id": 45160, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "Java": "interface Thingable {\n    String thing();\n}\n\nclass Delegator {\n    public Thingable delegate;\n\n    public String operation() {\n        if (delegate == null)\n            return \"default implementation\";\n        else\n            return delegate.thing();\n    }\n}\n\nclass Delegate implements Thingable {\n    public String thing() {\n        return \"delegate implementation\";\n    }\n}\n\n\n\npublic class DelegateExample {\n    public static void main(String[] args) {\n        \n        Delegator a = new Delegator();\n        assert a.operation().equals(\"default implementation\");\n\n        \n        Delegate d = new Delegate();\n        a.delegate = d;\n        assert a.operation().equals(\"delegate implementation\");\n\n        \n        a.delegate = new Thingable() {\n                public String thing() {\n                    return \"anonymous delegate implementation\";\n                }\n            };\n        assert a.operation().equals(\"anonymous delegate implementation\");\n    }\n}\n"}
{"id": 45161, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 45162, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "Java": "public class DivisorSum {\n    private static long divisorSum(long n) {\n        var total = 1L;\n        var power = 2L;\n        \n        for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n            total += power;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long sum = 1;\n            for (power = p; n % p == 0; power *= p, n /= p) {\n                sum += power;\n            }\n            total *= sum;\n        }\n        \n        if (n > 1) {\n            total *= n + 1;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n        for (long n = 1; n <= limit; ++n) {\n            System.out.printf(\"%4d\", divisorSum(n));\n            if (n % 10 == 0) {\n                System.out.println();\n            }\n        }\n    }\n}\n"}
{"id": 45163, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 45164, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 45165, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 45166, "name": "Enforced immutability", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n", "Java": "final int immutableInt = 4;\nint mutableInt = 4;\nmutableInt = 6; \nimmutableInt = 6; \n"}
{"id": 45167, "name": "Sutherland-Hodgman polygon clipping", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n", "Java": "import java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n    SutherlandHodgmanPanel panel;\n\n    public static void main(String[] args) {\n        JFrame f = new SutherlandHodgman();\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.setVisible(true);\n    }\n\n    public SutherlandHodgman() {\n        Container content = getContentPane();\n        content.setLayout(new BorderLayout());\n        panel = new SutherlandHodgmanPanel();\n        content.add(panel, BorderLayout.CENTER);\n        setTitle(\"SutherlandHodgman\");\n        pack();\n        setLocationRelativeTo(null);\n    }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n    List<double[]> subject, clipper, result;\n\n    public SutherlandHodgmanPanel() {\n        setPreferredSize(new Dimension(600, 500));\n\n        \n        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n        subject = new ArrayList<>(Arrays.asList(subjPoints));\n        result  = new ArrayList<>(subject);\n        clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n        clipPolygon();\n    }\n\n    private void clipPolygon() {\n        int len = clipper.size();\n        for (int i = 0; i < len; i++) {\n\n            int len2 = result.size();\n            List<double[]> input = result;\n            result = new ArrayList<>(len2);\n\n            double[] A = clipper.get((i + len - 1) % len);\n            double[] B = clipper.get(i);\n\n            for (int j = 0; j < len2; j++) {\n\n                double[] P = input.get((j + len2 - 1) % len2);\n                double[] Q = input.get(j);\n\n                if (isInside(A, B, Q)) {\n                    if (!isInside(A, B, P))\n                        result.add(intersection(A, B, P, Q));\n                    result.add(Q);\n                } else if (isInside(A, B, P))\n                    result.add(intersection(A, B, P, Q));\n            }\n        }\n    }\n\n    private boolean isInside(double[] a, double[] b, double[] c) {\n        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n    }\n\n    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n        double A1 = b[1] - a[1];\n        double B1 = a[0] - b[0];\n        double C1 = A1 * a[0] + B1 * a[1];\n\n        double A2 = q[1] - p[1];\n        double B2 = p[0] - q[0];\n        double C2 = A2 * p[0] + B2 * p[1];\n\n        double det = A1 * B2 - A2 * B1;\n        double x = (B2 * C1 - B1 * C2) / det;\n        double y = (A1 * C2 - A2 * C1) / det;\n\n        return new double[]{x, y};\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        Graphics2D g2 = (Graphics2D) g;\n        g2.translate(80, 60);\n        g2.setStroke(new BasicStroke(3));\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawPolygon(g2, subject, Color.blue);\n        drawPolygon(g2, clipper, Color.red);\n        drawPolygon(g2, result, Color.green);\n    }\n\n    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {\n        g2.setColor(color);\n        int len = points.size();\n        Line2D line = new Line2D.Double();\n        for (int i = 0; i < len; i++) {\n            double[] p1 = points.get(i);\n            double[] p2 = points.get((i + 1) % len);\n            line.setLine(p1[0], p1[1], p2[0], p2[1]);\n            g2.draw(line);\n        }\n    }\n}\n"}
{"id": 45168, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 45169, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 45170, "name": "Spiral matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n"}
{"id": 45171, "name": "Optional parameters", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n"}
{"id": 45172, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 45173, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 45174, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t    d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); \n\t\n\t\n\t  \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n"}
{"id": 45175, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 45176, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 45177, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 45178, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "Java": "import java.util.*;\n \nclass SOfN<T> {\n    private static final Random rand = new Random();\n \n    private List<T> sample;\n    private int i = 0;\n    private int n;\n\n    public SOfN(int _n) {\n        n = _n;\n        sample = new ArrayList<T>(n);\n    }\n\n    public List<T> process(T item) {\n        if (++i <= n) {\n            sample.add(item);\n        } else if (rand.nextInt(i) < n) {\n            sample.set(rand.nextInt(n), item);\n        }\n        return sample;\n    }\n}\n \npublic class AlgorithmS {\n    public static void main(String[] args) {\n        int[] bin = new int[10];\n        for (int trial = 0; trial < 100000; trial++) {\n            SOfN<Integer> s_of_n = new SOfN<Integer>(3);\n            for (int i = 0; i < 9; i++) s_of_n.process(i);\n            for (int s : s_of_n.process(9)) bin[s]++;\n        }\n        System.out.println(Arrays.toString(bin));\n    }\n}\n"}
{"id": 45179, "name": "Faulhaber's triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n"}
{"id": 45180, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 45181, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 45182, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 45183, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 45184, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 45185, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 45186, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 45187, "name": "Primes - allocate descendants to their ancestors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n"}
{"id": 45188, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 45189, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 45190, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "Java": "import java.util.ArrayList;\n\npublic class FirstClass{\n\t\n\tpublic interface Function<A,B>{\n\t\tB apply(A x);\n\t}\n\t\n\tpublic static <A,B,C> Function<A, C> compose(\n\t\t\tfinal Function<B, C> f, final Function<A, B> g) {\n\t\treturn new Function<A, C>() {\n\t\t\t@Override public C apply(A x) {\n\t\t\t\treturn f.apply(g.apply(x));\n\t\t\t}\n\t\t};\n\t}\n\t \n\tpublic static void main(String[] args){\n\t\tArrayList<Function<Double, Double>> functions =\n\t\t\tnew ArrayList<Function<Double,Double>>();\n\t\t\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.cos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.tan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tfunctions.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn x * x;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\n\t\tArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();\n\t\t\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.acos(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.atan(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tinverse.add(\n\t\t\t\tnew Function<Double, Double>(){\n\t\t\t\t\t@Override public Double apply(Double x){\n\t\t\t\t\t\treturn Math.sqrt(x);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tSystem.out.println(\"Compositions:\");\n\t\tfor(int i = 0; i < functions.size(); i++){\n\t\t\tSystem.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));\n\t\t}\n\t\tSystem.out.println(\"Hard-coded compositions:\");\n\t\tSystem.out.println(Math.cos(Math.acos(0.5)));\n\t\tSystem.out.println(Math.tan(Math.atan(0.5)));\n\t\tSystem.out.println(Math.pow(Math.sqrt(0.5), 2));\n\t}\n}\n"}
{"id": 45191, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 45192, "name": "XML_Output", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n"}
{"id": 45193, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 45194, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 45195, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 45196, "name": "Guess the number_With feedback (player)", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n", "Java": "import java.util.AbstractList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class GuessNumber {\n    public static final int LOWER = 0, UPPER = 100;\n    public static void main(String[] args) {\n\tSystem.out.printf(\"Instructions:\\n\" +\n\t\t\t  \"Think of integer number from %d (inclusive) to %d (exclusive) and\\n\" +\n\t\t\t  \"I will guess it. After each guess, you respond with L, H, or C depending\\n\" +\n\t\t\t  \"on if my guess was too low, too high, or correct.\\n\",\n\t\t\t  LOWER, UPPER);\n\tint result = Collections.binarySearch(new AbstractList<Integer>() {\n\t\tprivate final Scanner in = new Scanner(System.in);\n\t\tpublic int size() { return UPPER - LOWER; }\n\t\tpublic Integer get(int i) {\n\t\t    System.out.printf(\"My guess is: %d. Is it too high, too low, or correct? (H/L/C) \", LOWER+i);\n\t\t    String s = in.nextLine();\n\t\t    assert s.length() > 0;\n\t\t    switch (Character.toLowerCase(s.charAt(0))) {\n\t\t    case 'l':\n\t\t\treturn -1;\n\t\t    case 'h':\n\t\t\treturn 1;\n\t\t    case 'c':\n\t\t\treturn 0;\n\t\t    }\n\t\t    return -1;\n\t\t}\n\t    }, 0);\n\tif (result < 0)\n\t    System.out.println(\"That is impossible.\");\n\telse\n\t    System.out.printf(\"Your number is %d.\\n\", result);\n    }\n}\n"}
{"id": 45197, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 45198, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 45199, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 45200, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n    public static <T extends Comparable<? super T>> int[] bins(\n            List<? extends T> limits, Iterable<? extends T> data) {\n        int[] result = new int[limits.size() + 1];\n        for (T n : data) {\n            int i = Collections.binarySearch(limits, n);\n            if (i >= 0) {\n                \n                i = i+1;\n            } else {\n                \n                i = ~i;\n            }\n            result[i]++;\n        }\n        return result;\n    }\n\n    public static void printBins(List<?> limits, int[] bins) {\n        int n = limits.size();\n        if (n == 0) {\n            return;\n        }\n        assert n+1 == bins.length;\n        System.out.printf(\"           < %3s: %2d\\n\", limits.get(0), bins[0]);\n        for (int i = 1; i < n; i++) {\n            System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n        }\n        System.out.printf(\">= %3s          : %2d\\n\", limits.get(n-1), bins[n]);\n    }\n\n    public static void main(String[] args) {\n        List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n        List<Integer> data = Arrays.asList(\n            95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,\n            17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,\n            30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n        System.out.println(\"Example 1:\");\n        printBins(limits, bins(limits, data));\n\n        limits = Arrays.asList(14,  18,  249, 312, 389,\n                               392, 513, 591, 634, 720);\n        data = Arrays.asList(\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n            570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n            731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n            248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n            913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n            799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n            313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n            397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n            480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n            576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n            54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n            876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n            707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n            101, 684, 727, 749);\n\n        System.out.println();\n        System.out.println(\"Example 2:\");\n        printBins(limits, bins(limits, data));\n    }\n}\n"}
{"id": 45201, "name": "Fractal tree", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n    public FractalTree() {\n        super(\"Fractal Tree\");\n        setBounds(100, 100, 800, 600);\n        setResizable(false);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n    }\n\n    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n        g.drawLine(x1, y1, x2, y2);\n        drawTree(g, x2, y2, angle - 20, depth - 1);\n        drawTree(g, x2, y2, angle + 20, depth - 1);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        drawTree(g, 400, 500, -90, 9);\n    }\n\n    public static void main(String[] args) {\n        new FractalTree().setVisible(true);\n    }\n}\n"}
{"id": 45202, "name": "Colour pinstripe_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 45203, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 45204, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "Java": "class Doom {\n    public static void main(String[] args) {\n        final Date[] dates = {\n            new Date(1800,1,6),\n            new Date(1875,3,29),\n            new Date(1915,12,7),\n            new Date(1970,12,23),\n            new Date(2043,5,14),\n            new Date(2077,2,12),\n            new Date(2101,4,2)\n        };\n        \n        for (Date d : dates)\n            System.out.println(\n                String.format(\"%s: %s\", d.format(), d.weekday()));\n    }\n}\n\nclass Date {\n    private int year, month, day;\n    \n    private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n    private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n    public static final String[] weekdays = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    public Date(int year, int month, int day) {\n        this.year = year;\n        this.month = month;\n        this.day = day;\n    }\n    \n    public boolean isLeapYear() {\n        return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n    }\n    \n    public String format() {\n        return String.format(\"%02d/%02d/%04d\", month, day, year);\n    }\n    \n    public String weekday() {\n        final int c = year/100;\n        final int r = year%100;\n        final int s = r/12;\n        final int t = r%12;\n        \n        final int c_anchor = (5 * (c%4) + 2) % 7;\n        final int doom = (s + t + t/4 + c_anchor) % 7;\n        final int anchor = \n            isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n        \n        return weekdays[(doom + day - anchor + 7) % 7];\n    }\n}\n"}
{"id": 45205, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n"}
{"id": 45206, "name": "Animate a pendulum", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n"}
{"id": 45207, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 45208, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 45209, "name": "Create a file on magnetic tape", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n", "Java": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Collections;\n\npublic class CreateFile {\n    public static void main(String[] args) throws IOException {\n        String os = System.getProperty(\"os.name\");\n        if (os.contains(\"Windows\")) {\n            Path path = Paths.get(\"tape.file\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        } else {\n            Path path = Paths.get(\"/dev/tape\");\n            Files.write(path, Collections.singletonList(\"Hello World!\"));\n        }\n    }\n}\n"}
{"id": 45210, "name": "Sorting algorithms_Heapsort", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n", "Java": "public static void heapSort(int[] a){\n\tint count = a.length;\n\n\t\n\theapify(a, count);\n\n\tint end = count - 1;\n\twhile(end > 0){\n\t\t\n\t\t\n\t\tint tmp = a[end];\n\t\ta[end] = a[0];\n\t\ta[0] = tmp;\n\t\t\n\t\tsiftDown(a, 0, end - 1);\n\t\t\n\t\t\n\t\tend--;\n\t}\n}\n\npublic static void heapify(int[] a, int count){\n\t\n\tint start = (count - 2) / 2; \n\n\twhile(start >= 0){\n\t\t\n\t\t\n\t\t\n\t\tsiftDown(a, start, count - 1);\n\t\tstart--;\n\t}\n\t\n}\n\npublic static void siftDown(int[] a, int start, int end){\n\t\n\tint root = start;\n\n\twhile((root * 2 + 1) <= end){      \n\t\tint child = root * 2 + 1;           \n\t\t\n\t\tif(child + 1 <= end && a[child] < a[child + 1])\n\t\t\tchild = child + 1;           \n\t\tif(a[root] < a[child]){     \n\t\t\tint tmp = a[root];\n\t\t\ta[root] = a[child];\n\t\t\ta[child] = tmp;\n\t\t\troot = child;                \n\t\t}else\n\t\t\treturn;\n\t}\n}\n"}
{"id": 45211, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 45212, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 45213, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 45214, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 45215, "name": "Euler method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n"}
{"id": 45216, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 45217, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 45218, "name": "JortSort", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n"}
{"id": 45219, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 45220, "name": "Combinations and permutations", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n"}
{"id": 45221, "name": "Sort numbers lexicographically", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n"}
{"id": 45222, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 45223, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 45224, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "Java": "package stringlensort;\n\nimport java.io.PrintStream;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class ReportStringLengths {\n\n    public static void main(String[] args) {\n        String[] list = {\"abcd\", \"123456789\", \"abcdef\", \"1234567\"};\n        String[] strings = args.length > 0 ? args : list;\n\n        compareAndReportStringsLength(strings);\n    }\n\n        \n    public static void compareAndReportStringsLength(String[] strings) {\n        compareAndReportStringsLength(strings, System.out);\n    }\n\n    \n    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {\n        if (strings.length > 0) {\n            strings = strings.clone();\n            final String QUOTE = \"\\\"\";\n            Arrays.sort(strings, Comparator.comparing(String::length));\n            int min = strings[0].length();\n            int max = strings[strings.length - 1].length();\n            for (int i = strings.length - 1; i >= 0; i--) {\n                int length = strings[i].length();\n                String predicate;\n                if (length == max) {\n                    predicate = \"is the longest string\";\n                } else if (length == min) {\n                    predicate = \"is the shortest string\";\n                } else {\n                    predicate = \"is neither the longest nor the shortest string\";\n                }\n                \n                stream.println(QUOTE + strings[i] + QUOTE + \" has length \" + length\n                        + \" and \" + predicate);\n            }\n        }\n    }\n}\n"}
{"id": 45225, "name": "Sorting algorithms_Shell sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n"}
{"id": 45226, "name": "Doubly-linked list_Definition", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 45227, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 45228, "name": "Permutation test", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n", "Java": "public class PermutationTest {\n    private static final int[] data = new int[]{\n        85, 88, 75, 66, 25, 29, 83, 39, 97,\n        68, 41, 10, 49, 16, 65, 32, 92, 28, 98\n    };\n\n    private static int pick(int at, int remain, int accu, int treat) {\n        if (remain == 0) return (accu > treat) ? 1 : 0;\n        return pick(at - 1, remain - 1, accu + data[at - 1], treat)\n            + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);\n    }\n\n    public static void main(String[] args) {\n        int treat = 0;\n        double total = 1.0;\n        for (int i = 0; i <= 8; ++i) {\n            treat += data[i];\n        }\n        for (int i = 19; i >= 11; --i) {\n            total *= i;\n        }\n        for (int i = 9; i >= 1; --i) {\n            total /= i;\n        }\n        int gt = pick(19, 9, 0, treat);\n        int le = (int) (total - gt);\n        System.out.printf(\"<= : %f%%  %d\\n\", 100.0 * le / total, le);\n        System.out.printf(\" > : %f%%  %d\\n\", 100.0 * gt / total, gt);\n    }\n}\n"}
{"id": 45229, "name": "Möbius function", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n", "Java": "public class MöbiusFunction {\n\n    public static void main(String[] args) {\n        System.out.printf(\"First 199 terms of the möbius function are as follows:%n    \");\n        for ( int n = 1 ; n < 200 ; n++ ) {\n            System.out.printf(\"%2d  \", möbiusFunction(n));\n            if ( (n+1) % 20 == 0 ) {\n                System.out.printf(\"%n\");\n            }\n        }\n    }\n    \n    private static int MU_MAX = 1_000_000;\n    private static int[] MU = null;\n    \n    \n    private static int möbiusFunction(int n) {\n        if ( MU != null ) {\n            return MU[n];\n        }\n        \n        \n        MU = new int[MU_MAX+1];\n        int sqrt = (int) Math.sqrt(MU_MAX);\n        for ( int i = 0 ; i < MU_MAX ; i++ ) {\n            MU[i] = 1;\n        }\n        \n        for ( int i = 2 ; i <= sqrt ; i++ ) {\n            if ( MU[i] == 1 ) {\n                \n                for ( int j = i ; j <= MU_MAX ; j += i ) {\n                    MU[j] *= -i;\n                }\n                \n                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {\n                    MU[j] = 0;\n                }\n            }\n        }\n        \n        for ( int i = 2 ; i <= MU_MAX ; i++ ) {\n            if ( MU[i] == i ) {\n                MU[i] = 1;\n            }\n            else if ( MU[i] == -i ) {\n                MU[i] = -1;\n            }\n            else if ( MU[i] < 0 ) {\n                MU[i] = 1;               \n            }\n            else if ( MU[i] > 0 ) {\n                MU[i] = -1;\n            }\n        }\n        return MU[n];\n    }\n\n}\n"}
{"id": 45230, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 45231, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 45232, "name": "Sorting algorithms_Permutation sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class PermutationSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] a={3,2,1,8,9,4,6};\n\t\tSystem.out.println(\"Unsorted: \" + Arrays.toString(a));\n\t\ta=pSort(a);\n\t\tSystem.out.println(\"Sorted: \" + Arrays.toString(a));\n\t}\n\tpublic static int[] pSort(int[] a)\n\t{\n\t\tList<int[]> list=new ArrayList<int[]>();\n\t\tpermute(a,a.length,list);\n\t\tfor(int[] x : list)\n\t\t\tif(isSorted(x))\n\t\t\t\treturn x;\n\t\treturn a;\n\t}\n\tprivate static void permute(int[] a, int n, List<int[]> list) \n\t{\n\t\tif (n == 1) \n\t\t{\n\t\t\tint[] b=new int[a.length];\n\t\t\tSystem.arraycopy(a, 0, b, 0, a.length);\n\t\t\tlist.add(b);\n\t\t    return;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) \n\t\t{\n\t\t        swap(a, i, n-1);\n\t\t        permute(a, n-1, list);\n\t\t        swap(a, i, n-1);\n\t\t }\n\t}\n\tprivate static boolean isSorted(int[] a)\n\t{\n\t\tfor(int i=1;i<a.length;i++)\n\t\t\tif(a[i-1]>a[i])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate static void swap(int[] arr,int i, int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n}\n"}
{"id": 45233, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 45234, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 45235, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 45236, "name": "Entropy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n", "Java": "import java.lang.Math;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class REntropy {\n\n  @SuppressWarnings(\"boxing\")\n  public static double getShannonEntropy(String s) {\n    int n = 0;\n    Map<Character, Integer> occ = new HashMap<>();\n\n    for (int c_ = 0; c_ < s.length(); ++c_) {\n      char cx = s.charAt(c_);\n      if (occ.containsKey(cx)) {\n        occ.put(cx, occ.get(cx) + 1);\n      } else {\n        occ.put(cx, 1);\n      }\n      ++n;\n    }\n\n    double e = 0.0;\n    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {\n      char cx = entry.getKey();\n      double p = (double) entry.getValue() / n;\n      e += p * log2(p);\n    }\n    return -e;\n  }\n\n  private static double log2(double a) {\n    return Math.log(a) / Math.log(2);\n  }\n  public static void main(String[] args) {\n    String[] sstr = {\n      \"1223334444\",\n      \"1223334444555555555\", \n      \"122333\", \n      \"1227774444\",\n      \"aaBBcccDDDD\",\n      \"1234567890abcdefghijklmnopqrstuvwxyz\",\n      \"Rosetta Code\",\n    };\n\n    for (String ss : sstr) {\n      double entropy = REntropy.getShannonEntropy(ss);\n      System.out.printf(\"Shannon entropy of %40s: %.12f%n\", \"\\\"\" + ss + \"\\\"\", entropy);\n    }\n    return;\n  }\n}\n"}
{"id": 45237, "name": "Tokenize a string with escaping", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n"}
{"id": 45238, "name": "Hello world_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 45239, "name": "Sexy primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class SexyPrimes {\n\n    public static void main(String[] args) {\n        sieve();\n        int pairs = 0;\n        List<String> pairList = new ArrayList<>();\n        int triples = 0;\n        List<String> tripleList = new ArrayList<>();\n        int quadruplets = 0;\n        List<String> quadrupletList = new ArrayList<>();\n        int unsexyCount = 1;  \n        List<String> unsexyList = new ArrayList<>();\n        for ( int i = 3 ; i < MAX ; i++ ) {\n            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {\n                pairs++;\n                pairList.add((i-6) + \" \" + i);\n                if ( pairList.size() > 5 ) {\n                    pairList.remove(0);\n                }\n            }\n            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {\n                unsexyCount++;\n                unsexyList.add(\"\" + i);\n                if ( unsexyList.size() > 10 ) {\n                    unsexyList.remove(0);\n                }\n            }\n            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {\n                triples++;\n                tripleList.add((i-12) + \" \" + (i-6) + \" \" + i);\n                if ( tripleList.size() > 5 ) {\n                    tripleList.remove(0);\n                }\n            }\n            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {\n                quadruplets++;\n                quadrupletList.add((i-18) + \" \" + (i-12) + \" \" + (i-6) + \" \" + i);\n                if ( quadrupletList.size() > 5 ) {\n                    quadrupletList.remove(0);\n                }\n            }\n        }\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, pairs);\n        System.out.printf(\"The last 5 sexy pairs:%n  %s%n%n\", pairList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy triples less than %,d = %,d%n\", MAX, triples);\n        System.out.printf(\"The last 5 sexy triples:%n  %s%n%n\", tripleList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of sexy quadruplets less than %,d = %,d%n\", MAX, quadruplets);\n        System.out.printf(\"The last 5 sexy quadruplets:%n  %s%n%n\", quadrupletList.toString().replaceAll(\", \", \"], [\"));\n        System.out.printf(\"Count of unsexy primes less than %,d = %,d%n\", MAX, unsexyCount);\n        System.out.printf(\"The last 10 unsexy primes:%n  %s%n%n\", unsexyList.toString().replaceAll(\", \", \"], [\"));\n    }\n\n    private static int MAX = 1_000_035;\n    private static boolean[] primes = new boolean[MAX];\n\n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n}\n"}
{"id": 45240, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 45241, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 45242, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 45243, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 45244, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n"}
{"id": 45245, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n"}
{"id": 45246, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 45247, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 45248, "name": "Discordian date", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n", "Java": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\npublic class DiscordianDate {\n    final static String[] seasons = {\"Chaos\", \"Discord\", \"Confusion\",\n        \"Bureaucracy\", \"The Aftermath\"};\n\n    final static String[] weekday = {\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"};\n\n    final static String[] apostle = {\"Mungday\", \"Mojoday\", \"Syaday\",\n        \"Zaraday\", \"Maladay\"};\n\n    final static String[] holiday = {\"Chaoflux\", \"Discoflux\", \"Confuflux\",\n        \"Bureflux\", \"Afflux\"};\n\n    public static String discordianDate(final GregorianCalendar date) {\n        int y = date.get(Calendar.YEAR);\n        int yold = y + 1166;\n        int dayOfYear = date.get(Calendar.DAY_OF_YEAR);\n\n        if (date.isLeapYear(y)) {\n            if (dayOfYear == 60)\n                return \"St. Tib's Day, in the YOLD \" + yold;\n            else if (dayOfYear > 60)\n                dayOfYear--;\n        }\n\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        if (seasonDay == 5)\n            return apostle[dayOfYear / 73] + \", in the YOLD \" + yold;\n        if (seasonDay == 50)\n            return holiday[dayOfYear / 73] + \", in the YOLD \" + yold;\n\n        String season = seasons[dayOfYear / 73];\n        String dayOfWeek = weekday[dayOfYear % 5];\n\n        return String.format(\"%s, day %s of %s in the YOLD %s\",\n                dayOfWeek, seasonDay, season, yold);\n    }\n\n    public static void main(String[] args) {\n\n        System.out.println(discordianDate(new GregorianCalendar()));\n\n        test(2010, 6, 22, \"Pungenday, day 57 of Confusion in the YOLD 3176\");\n        test(2012, 1, 28, \"Prickle-Prickle, day 59 of Chaos in the YOLD 3178\");\n        test(2012, 1, 29, \"St. Tib's Day, in the YOLD 3178\");\n        test(2012, 2, 1, \"Setting Orange, day 60 of Chaos in the YOLD 3178\");\n        test(2010, 0, 5, \"Mungday, in the YOLD 3176\");\n        test(2011, 4, 3, \"Discoflux, in the YOLD 3177\");\n        test(2015, 9, 19, \"Boomtime, day 73 of Bureaucracy in the YOLD 3181\");\n    }\n\n    private static void test(int y, int m, int d, final String result) {\n        assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));\n    }\n}\n"}
{"id": 45249, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 45250, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "Java": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class FlippingBitsGame extends JPanel {\n    final int maxLevel = 7;\n    final int minLevel = 3;\n\n    private Random rand = new Random();\n    private int[][] grid, target;\n    private Rectangle box;\n    private int n = maxLevel;\n    private boolean solved = true;\n\n    FlippingBitsGame() {\n        setPreferredSize(new Dimension(640, 640));\n        setBackground(Color.white);\n        setFont(new Font(\"SansSerif\", Font.PLAIN, 18));\n\n        box = new Rectangle(120, 90, 400, 400);\n\n        startNewGame();\n\n        addMouseListener(new MouseAdapter() {\n            @Override\n            public void mousePressed(MouseEvent e) {\n                if (solved) {\n                    startNewGame();\n                } else {\n                    int x = e.getX();\n                    int y = e.getY();\n\n                    if (box.contains(x, y))\n                        return;\n\n                    if (x > box.x && x < box.x + box.width) {\n                        flipCol((x - box.x) / (box.width / n));\n\n                    } else if (y > box.y && y < box.y + box.height)\n                        flipRow((y - box.y) / (box.height / n));\n\n                    if (solved(grid, target))\n                        solved = true;\n\n                    printGrid(solved ? \"Solved!\" : \"The board\", grid);\n                }\n                repaint();\n            }\n        });\n    }\n\n    void startNewGame() {\n        if (solved) {\n\n            n = (n == maxLevel) ? minLevel : n + 1;\n\n            grid = new int[n][n];\n            target = new int[n][n];\n\n            do {\n                shuffle();\n\n                for (int i = 0; i < n; i++)\n                    target[i] = Arrays.copyOf(grid[i], n);\n\n                shuffle();\n\n            } while (solved(grid, target));\n\n            solved = false;\n            printGrid(\"The target\", target);\n            printGrid(\"The board\", grid);\n        }\n    }\n\n    void printGrid(String msg, int[][] g) {\n        System.out.println(msg);\n        for (int[] row : g)\n            System.out.println(Arrays.toString(row));\n        System.out.println();\n    }\n\n    boolean solved(int[][] a, int[][] b) {\n        for (int i = 0; i < n; i++)\n            if (!Arrays.equals(a[i], b[i]))\n                return false;\n        return true;\n    }\n\n    void shuffle() {\n        for (int i = 0; i < n * n; i++) {\n            if (rand.nextBoolean())\n                flipRow(rand.nextInt(n));\n            else\n                flipCol(rand.nextInt(n));\n        }\n    }\n\n    void flipRow(int r) {\n        for (int c = 0; c < n; c++) {\n            grid[r][c] ^= 1;\n        }\n    }\n\n    void flipCol(int c) {\n        for (int[] row : grid) {\n            row[c] ^= 1;\n        }\n    }\n\n    void drawGrid(Graphics2D g) {\n        g.setColor(getForeground());\n\n        if (solved)\n            g.drawString(\"Solved! Click here to play again.\", 180, 600);\n        else\n            g.drawString(\"Click next to a row or a column to flip.\", 170, 600);\n\n        int size = box.width / n;\n\n        for (int r = 0; r < n; r++)\n            for (int c = 0; c < n; c++) {\n                g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(getBackground());\n                g.drawRect(box.x + c * size, box.y + r * size, size, size);\n                g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);\n                g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);\n            }\n    }\n\n    @Override\n    public void paintComponent(Graphics gg) {\n        super.paintComponent(gg);\n        Graphics2D g = (Graphics2D) gg;\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n\n        drawGrid(g);\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"Flipping Bits Game\");\n            f.setResizable(false);\n            f.add(new FlippingBitsGame(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 45251, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 45252, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 45253, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "Java": "import java.math.*;\n\npublic class Hickerson {\n\n    final static String LN2 = \"0.693147180559945309417232121458\";\n\n    public static void main(String[] args) {\n        for (int n = 1; n <= 17; n++)\n            System.out.printf(\"%2s is almost integer: %s%n\", n, almostInteger(n));\n    }\n\n    static boolean almostInteger(int n) {\n        BigDecimal a = new BigDecimal(LN2);\n        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));\n\n        long f = n;\n        while (--n > 1)\n            f *= n;\n\n        BigDecimal b = new BigDecimal(f);\n        b = b.divide(a, MathContext.DECIMAL128);\n\n        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);\n\n        return c.toString().matches(\"0|9\");\n    }\n}\n"}
{"id": 45254, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 45255, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 45256, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n"}
{"id": 45257, "name": "Sorting algorithms_Patience sort", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n", "Java": "import java.util.*;\n\npublic class PatienceSort {\n    public static <E extends Comparable<? super E>> void sort (E[] n) {\n        List<Pile<E>> piles = new ArrayList<Pile<E>>();\n        \n        for (E x : n) {\n            Pile<E> newPile = new Pile<E>();\n            newPile.push(x);\n            int i = Collections.binarySearch(piles, newPile);\n            if (i < 0) i = ~i;\n            if (i != piles.size())\n                piles.get(i).push(x);\n            else\n                piles.add(newPile);\n        }\n \n        \n        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);\n        for (int c = 0; c < n.length; c++) {\n            Pile<E> smallPile = heap.poll();\n            n[c] = smallPile.pop();\n            if (!smallPile.isEmpty())\n                heap.offer(smallPile);\n        }\n        assert(heap.isEmpty());\n    }\n \n    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {\n        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }\n    }\n\n    public static void main(String[] args) {\n\tInteger[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};\n\tsort(a);\n\tSystem.out.println(Arrays.toString(a));\n    }\n}\n"}
{"id": 45258, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 45259, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "Java": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n    public static void main(String[] args) {\n        SequenceMutation sm = new SequenceMutation();\n        sm.setWeight(OP_CHANGE, 3);\n        String sequence = sm.generateSequence(250);\n        System.out.println(\"Initial sequence:\");\n        printSequence(sequence);\n        int count = 10;\n        for (int i = 0; i < count; ++i)\n            sequence = sm.mutateSequence(sequence);\n        System.out.println(\"After \" + count + \" mutations:\");\n        printSequence(sequence);\n    }\n\n    public SequenceMutation() {\n        totalWeight_ = OP_COUNT;\n        Arrays.fill(operationWeight_, 1);\n    }\n\n    public String generateSequence(int length) {\n        char[] ch = new char[length];\n        for (int i = 0; i < length; ++i)\n            ch[i] = getRandomBase();\n        return new String(ch);\n    }\n\n    public void setWeight(int operation, int weight) {\n        totalWeight_ -= operationWeight_[operation];\n        operationWeight_[operation] = weight;\n        totalWeight_ += weight;\n    }\n\n    public String mutateSequence(String sequence) {\n        char[] ch = sequence.toCharArray();\n        int pos = random_.nextInt(ch.length);\n        int operation = getRandomOperation();\n        if (operation == OP_CHANGE) {\n            char b = getRandomBase();\n            System.out.println(\"Change base at position \" + pos + \" from \"\n                               + ch[pos] + \" to \" + b);\n            ch[pos] = b;\n        } else if (operation == OP_ERASE) {\n            System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n            char[] newCh = new char[ch.length - 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n            ch = newCh;\n        } else if (operation == OP_INSERT) {\n            char b = getRandomBase();\n            System.out.println(\"Insert base \" + b + \" at position \" + pos);\n            char[] newCh = new char[ch.length + 1];\n            System.arraycopy(ch, 0, newCh, 0, pos);\n            System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n            newCh[pos] = b;\n            ch = newCh;\n        }\n        return new String(ch);\n    }\n\n    public static void printSequence(String sequence) {\n        int[] count = new int[BASES.length];\n        for (int i = 0, n = sequence.length(); i < n; ++i) {\n            if (i % 50 == 0) {\n                if (i != 0)\n                    System.out.println();\n                System.out.printf(\"%3d: \", i);\n            }\n            char ch = sequence.charAt(i);\n            System.out.print(ch);\n            for (int j = 0; j < BASES.length; ++j) {\n                if (BASES[j] == ch) {\n                    ++count[j];\n                    break;\n                }\n            }\n        }\n        System.out.println();\n        System.out.println(\"Base counts:\");\n        int total = 0;\n        for (int j = 0; j < BASES.length; ++j) {\n            total += count[j];\n            System.out.print(BASES[j] + \": \" + count[j] + \", \");\n        }\n        System.out.println(\"Total: \" + total);\n    }\n\n    private char getRandomBase() {\n        return BASES[random_.nextInt(BASES.length)];\n    }\n\n    private int getRandomOperation() {\n        int n = random_.nextInt(totalWeight_), op = 0;\n        for (int weight = 0; op < OP_COUNT; ++op) {\n            weight += operationWeight_[op];\n            if (n < weight)\n                break;\n        }\n        return op;\n    }\n\n    private final Random random_ = new Random();\n    private int[] operationWeight_ = new int[OP_COUNT];\n    private int totalWeight_ = 0;\n\n    private static final int OP_CHANGE = 0;\n    private static final int OP_ERASE = 1;\n    private static final int OP_INSERT = 2;\n    private static final int OP_COUNT = 3;\n    private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}\n"}
{"id": 45260, "name": "Tau number", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n", "Java": "public class Tau {\n    private static long divisorCount(long n) {\n        long total = 1;\n        \n        for (; (n & 1) == 0; n >>= 1) {\n            ++total;\n        }\n        \n        for (long p = 3; p * p <= n; p += 2) {\n            long count = 1;\n            for (; n % p == 0; n /= p) {\n                ++count;\n            }\n            total *= count;\n        }\n        \n        if (n > 1) {\n            total *= 2;\n        }\n        return total;\n    }\n\n    public static void main(String[] args) {\n        final long limit = 100;\n        System.out.printf(\"The first %d tau numbers are:%n\", limit);\n        long count = 0;\n        for (long n = 1; count < limit; ++n) {\n            if (n % divisorCount(n) == 0) {\n                System.out.printf(\"%6d\", n);\n                ++count;\n                if (count % 10 == 0) {\n                    System.out.println();\n                }\n            }\n        }\n    }\n}\n"}
{"id": 45261, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 45262, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 45263, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 45264, "name": "Partition function P", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n", "Java": "import java.math.BigInteger;\n\npublic class PartitionFunction {\n    public static void main(String[] args) {\n        long start = System.currentTimeMillis();\n        BigInteger result = partitions(6666);\n        long end = System.currentTimeMillis();\n        System.out.println(\"P(6666) = \" + result);\n        System.out.printf(\"elapsed time: %d milliseconds\\n\", end - start);\n    }\n\n    private static BigInteger partitions(int n) {\n        BigInteger[] p = new BigInteger[n + 1];\n        p[0] = BigInteger.ONE;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = BigInteger.ZERO;\n            for (int k = 1; ; ++k) {\n                int j = (k * (3 * k - 1))/2;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n                j += k;\n                if (j > i)\n                    break;\n                if ((k & 1) != 0)\n                    p[i] = p[i].add(p[i - j]);\n                else\n                    p[i] = p[i].subtract(p[i - j]);\n            }\n        }\n        return p[n];\n    }\n}\n"}
{"id": 45265, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n"}
{"id": 45266, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "Java": "import static java.lang.Math.*;\n\npublic class RayCasting {\n\n    static boolean intersects(int[] A, int[] B, double[] P) {\n        if (A[1] > B[1])\n            return intersects(B, A, P);\n\n        if (P[1] == A[1] || P[1] == B[1])\n            P[1] += 0.0001;\n\n        if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))\n            return false;\n\n        if (P[0] < min(A[0], B[0]))\n            return true;\n\n        double red = (P[1] - A[1]) / (double) (P[0] - A[0]);\n        double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);\n        return red >= blue;\n    }\n\n    static boolean contains(int[][] shape, double[] pnt) {\n        boolean inside = false;\n        int len = shape.length;\n        for (int i = 0; i < len; i++) {\n            if (intersects(shape[i], shape[(i + 1) % len], pnt))\n                inside = !inside;\n        }\n        return inside;\n    }\n\n    public static void main(String[] a) {\n        double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},\n        {20, 10}, {16, 10}, {20, 20}};\n\n        for (int[][] shape : shapes) {\n            for (double[] pnt : testPoints)\n                System.out.printf(\"%7s \", contains(shape, pnt));\n            System.out.println();\n        }\n    }\n\n    final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};\n\n    final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},\n    {5, 5}, {15, 5}, {15, 15}, {5, 15}};\n\n    final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},\n    {20, 20}, {20, 0}};\n\n    final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},\n    {6, 20}, {0, 10}};\n\n    final static int[][][] shapes = {square, squareHole, strange, hexagon};\n}\n"}
{"id": 45267, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n"}
{"id": 45268, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "Java": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n    public static void main(String[] args) {\n        Pt a = Pt.fromY(1);\n        Pt b = Pt.fromY(2);\n        System.out.printf(\"a = %s%n\", a);\n        System.out.printf(\"b = %s%n\", b);\n        Pt c = a.plus(b);\n        System.out.printf(\"c = a + b = %s%n\", c);\n        Pt d = c.neg();\n        System.out.printf(\"d = -c = %s%n\", d);\n        System.out.printf(\"c + d = %s%n\", c.plus(d));\n        System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n        System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n    }\n}\n\nclass Pt {\n    final static int bCoeff = 7;\n\n    double x, y;\n\n    Pt(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static Pt zero() {\n        return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n    }\n\n    boolean isZero() {\n        return this.x > 1e20 || this.x < -1e20;\n    }\n\n    static Pt fromY(double y) {\n        return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n    }\n\n    Pt dbl() {\n        if (isZero())\n            return this;\n        double L = (3 * this.x * this.x) / (2 * this.y);\n        double x2 = pow(L, 2) - 2 * this.x;\n        return new Pt(x2, L * (this.x - x2) - this.y);\n    }\n\n    Pt neg() {\n        return new Pt(this.x, -this.y);\n    }\n\n    Pt plus(Pt q) {\n        if (this.x == q.x && this.y == q.y)\n            return dbl();\n\n        if (isZero())\n            return q;\n\n        if (q.isZero())\n            return this;\n\n        double L = (q.y - this.y) / (q.x - this.x);\n        double xx = pow(L, 2) - this.x - q.x;\n        return new Pt(xx, L * (this.x - xx) - this.y);\n    }\n\n    Pt mult(int n) {\n        Pt r = Pt.zero();\n        Pt p = this;\n        for (int i = 1; i <= n; i <<= 1) {\n            if ((i & n) != 0)\n                r = r.plus(p);\n            p = p.dbl();\n        }\n        return r;\n    }\n\n    @Override\n    public String toString() {\n        if (isZero())\n            return \"Zero\";\n        return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n    }\n}\n"}
{"id": 45269, "name": "Count occurrences of a substring", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n", "Java": "public class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) / subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n"}
{"id": 45270, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 45271, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "Java": "public class PrimeDigits {\n    private static boolean primeDigitsSum13(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int r = n % 10;\n            if (r != 2 && r != 3 && r != 5 && r != 7) {\n                return false;\n            }\n            n /= 10;\n            sum += r;\n        }\n        return sum == 13;\n    }\n\n    public static void main(String[] args) {\n        \n        int c = 0;\n        for (int i = 1; i < 1_000_000; i++) {\n            if (primeDigitsSum13(i)) {\n                System.out.printf(\"%6d \", i);\n                if (c++ == 10) {\n                    c = 0;\n                    System.out.println();\n                }\n            }\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 45272, "name": "String comparison", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n", "Java": "public class Compare\n{\n\t\n    \n    public static void compare (String A, String B)\n    {\n        if (A.equals(B))\n            System.debug(A + ' and  ' + B + ' are lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not lexically equal.');\n\n        if (A.equalsIgnoreCase(B))\n            System.debug(A + ' and  ' + B + ' are case-insensitive lexically equal.');\n        else\n            System.debug(A + ' and  ' + B + ' are not case-insensitive lexically equal.');\n \n        if (A.compareTo(B) < 0)\n            System.debug(A + ' is lexically before ' + B);\n        else if (A.compareTo(B) > 0)\n            System.debug(A + ' is lexically after ' + B);\n \n        if (A.compareTo(B) >= 0)\n            System.debug(A + ' is not lexically before ' + B);\n        if (A.compareTo(B) <= 0)\n            System.debug(A + ' is not lexically after ' + B);\n \n        System.debug('The lexical relationship is: ' + A.compareTo(B));\n    }\n}\n"}
{"id": 45273, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "Java": "import java.io.*;\nimport java.nio.channels.*;\nimport java.util.Date;\n\npublic class TakeNotes {\n    public static void main(String[] args) throws IOException {\n        if (args.length > 0) {\n            PrintStream ps = new PrintStream(new FileOutputStream(\"notes.txt\", true));\n            ps.println(new Date());\n            ps.print(\"\\t\" + args[0]);\n            for (int i = 1; i < args.length; i++)\n                ps.print(\" \" + args[i]);\n            ps.println();\n            ps.close();\n        } else {\n            FileChannel fc = new FileInputStream(\"notes.txt\").getChannel();\n            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));\n            fc.close();\n        }\n    }\n}\n"}
{"id": 45274, "name": "Thiele's interpolation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n", "Java": "import static java.lang.Math.*;\n\npublic class Test {\n    final static int N = 32;\n    final static int N2 = (N * (N - 1) / 2);\n    final static double STEP = 0.05;\n\n    static double[] xval = new double[N];\n    static double[] t_sin = new double[N];\n    static double[] t_cos = new double[N];\n    static double[] t_tan = new double[N];\n\n    static double[] r_sin = new double[N2];\n    static double[] r_cos = new double[N2];\n    static double[] r_tan = new double[N2];\n\n    static double rho(double[] x, double[] y, double[] r, int i, int n) {\n        if (n < 0)\n            return 0;\n\n        if (n == 0)\n            return y[i];\n\n        int idx = (N - 1 - n) * (N - n) / 2 + i;\n        if (r[idx] != r[idx])\n            r[idx] = (x[i] - x[i + n])\n                    / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n                    + rho(x, y, r, i + 1, n - 2);\n\n        return r[idx];\n    }\n\n    static double thiele(double[] x, double[] y, double[] r, double xin, int n) {\n        if (n > N - 1)\n            return 1;\n        return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n                + (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i < N; i++) {\n            xval[i] = i * STEP;\n            t_sin[i] = sin(xval[i]);\n            t_cos[i] = cos(xval[i]);\n            t_tan[i] = t_sin[i] / t_cos[i];\n        }\n\n        for (int i = 0; i < N2; i++)\n            r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN;\n\n        System.out.printf(\"%16.14f%n\", 6 * thiele(t_sin, xval, r_sin, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 3 * thiele(t_cos, xval, r_cos, 0.5, 0));\n        System.out.printf(\"%16.14f%n\", 4 * thiele(t_tan, xval, r_tan, 1.0, 0));\n    }\n}\n"}
{"id": 45275, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n"}
{"id": 45276, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "Java": "import java.util.*;\n\npublic class FWord {\n    private  String fWord0 = \"\";\n    private  String fWord1 = \"\";\n\n    private String nextFWord () {\n        final String result;\n        \n        if ( \"\".equals ( fWord1 ) )      result = \"1\";\n        else if ( \"\".equals ( fWord0 ) ) result = \"0\";\n        else                             result = fWord1 + fWord0;\n\n        fWord0 = fWord1;\n        fWord1 = result;\n\n        return result;\n    }\n\n    public static double entropy ( final String source ) {\n        final int                        length = source.length ();\n        final Map < Character, Integer > counts = new HashMap < Character, Integer > ();\n         double                     result = 0.0;\n \n        for ( int i = 0; i < length; i++ ) {\n            final char c = source.charAt ( i );\n\n            if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );\n            else                            counts.put ( c, 1 );\n        }\n\n        for ( final int count : counts.values () ) {\n            final double proportion = ( double ) count / length;\n\n            result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );\n        }\n\n        return result;\n    }\n\n    public static void main ( final String [] args ) {\n        final FWord fWord = new FWord ();\n\n        for ( int i = 0; i < 37;  ) {\n            final String word = fWord.nextFWord ();\n\n            System.out.printf ( \"%3d %10d %s %n\", ++i, word.length (), entropy ( word ) );\n        }\n    }\n}\n"}
{"id": 45277, "name": "Angles (geometric), normalization and conversion", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n", "Java": "import java.text.DecimalFormat;\n\n\n\npublic class AnglesNormalizationAndConversion {\n\n    public static void main(String[] args) {\n        DecimalFormat formatAngle = new DecimalFormat(\"######0.000000\");\n        DecimalFormat formatConv = new DecimalFormat(\"###0.0000\");\n        System.out.printf(\"                               degrees    gradiens        mils     radians%n\");\n        for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {\n            for ( String units : new String[] {\"degrees\", \"gradiens\", \"mils\", \"radians\"}) {\n                double d = 0, g = 0, m = 0, r = 0;\n                switch (units) {\n                case \"degrees\":\n                    d = d2d(angle);\n                    g = d2g(d);\n                    m = d2m(d);\n                    r = d2r(d);\n                    break;\n                case \"gradiens\":\n                    g = g2g(angle);\n                    d = g2d(g);\n                    m = g2m(g);\n                    r = g2r(g);\n                    break;\n                case \"mils\":\n                    m = m2m(angle);\n                    d = m2d(m);\n                    g = m2g(m);\n                    r = m2r(m);\n                    break;\n                case \"radians\":\n                    r = r2r(angle);\n                    d = r2d(r);\n                    g = r2g(r);\n                    m = r2m(r);\n                    break;\n                }\n                System.out.printf(\"%15s  %8s = %10s  %10s  %10s  %10s%n\", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));\n            }\n        }\n    }\n\n    private static final double DEGREE = 360D;\n    private static final double GRADIAN = 400D;\n    private static final double MIL = 6400D;\n    private static final double RADIAN = (2 * Math.PI);\n    \n    private static double d2d(double a) {\n        return a % DEGREE;\n    }\n    private static double d2g(double a) {\n        return a * (GRADIAN / DEGREE);\n    }\n    private static double d2m(double a) {\n        return a * (MIL / DEGREE);\n    }\n    private static double d2r(double a) {\n        return a * (RADIAN / 360);\n    }\n\n    private static double g2d(double a) {\n        return a * (DEGREE / GRADIAN);\n    }\n    private static double g2g(double a) {\n        return a % GRADIAN;\n    }\n    private static double g2m(double a) {\n        return a * (MIL / GRADIAN);\n    }\n    private static double g2r(double a) {\n        return a * (RADIAN / GRADIAN);\n    }\n    \n    private static double m2d(double a) {\n        return a * (DEGREE / MIL);\n    }\n    private static double m2g(double a) {\n        return a * (GRADIAN / MIL);\n    }\n    private static double m2m(double a) {\n        return a % MIL;\n    }\n    private static double m2r(double a) {\n        return a * (RADIAN / MIL);\n    }\n    \n    private static double r2d(double a) {\n        return a * (DEGREE / RADIAN);\n    }\n    private static double r2g(double a) {\n        return a * (GRADIAN / RADIAN);\n    }\n    private static double r2m(double a) {\n        return a * (MIL / RADIAN);\n    }\n    private static double r2r(double a) {\n        return a % RADIAN;\n    }\n    \n}\n"}
{"id": 45278, "name": "Find common directory path", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n", "Java": "public class CommonPath {\n\tpublic static String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\tfor(int i = 0; i < paths.length; i++){\n\t\t\tfolders[i] = paths[i].split(\"/\"); \n\t\t}\n\t\tfor(int j = 0; j < folders[0].length; j++){\n\t\t\tString thisFolder = folders[0][j]; \n\t\t\tboolean allMatched = true; \n\t\t\tfor(int i = 1; i < folders.length && allMatched; i++){ \n\t\t\t\tif(folders[i].length < j){ \n\t\t\t\t\tallMatched = false; \n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tallMatched &= folders[i][j].equals(thisFolder); \n\t\t\t}\n\t\t\tif(allMatched){ \n\t\t\t\tcommonPath += thisFolder + \"/\"; \n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn commonPath;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString[] paths = { \"/home/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths));\n\t\t\n\t\tString[] paths2 = { \"/hame/user1/tmp/coverage/test\",\n\t\t\t\t \"/home/user1/tmp/covert/operator\",\n\t\t\t\t \"/home/user1/tmp/coven/members\"};\n\t\tSystem.out.println(commonPath(paths2));\n\t}\n}\n"}
{"id": 45279, "name": "Verify distribution uniformity_Naive", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport java.util.function.IntSupplier;\n\npublic class Test {\n\n    static void distCheck(IntSupplier f, int nRepeats, double delta) {\n        Map<Integer, Integer> counts = new HashMap<>();\n\n        for (int i = 0; i < nRepeats; i++)\n            counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);\n\n        double target = nRepeats / (double) counts.size();\n        int deltaCount = (int) (delta / 100.0 * target);\n\n        counts.forEach((k, v) -> {\n            if (abs(target - v) >= deltaCount)\n                System.out.printf(\"distribution potentially skewed \"\n                        + \"for '%s': '%d'%n\", k, v);\n        });\n\n        counts.keySet().stream().sorted().forEach(k\n                -> System.out.printf(\"%d %d%n\", k, counts.get(k)));\n    }\n\n    public static void main(String[] a) {\n        distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);\n    }\n}\n"}
{"id": 45280, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n"}
{"id": 45281, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class SterlingNumbersSecondKind {\n\n    public static void main(String[] args) {\n        System.out.println(\"Stirling numbers of the second kind:\");\n        int max = 12;\n        System.out.printf(\"n/k\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%10d\", n);\n        }\n        System.out.printf(\"%n\");\n        for ( int n = 0 ; n <= max ; n++ ) {\n            System.out.printf(\"%-3d\", n);\n            for ( int k = 0 ; k <= n ; k++ ) {\n                System.out.printf(\"%10s\", sterling2(n, k));\n            }\n            System.out.printf(\"%n\");\n        }\n        System.out.println(\"The maximum value of S2(100, k) = \");\n        BigInteger previous = BigInteger.ZERO;\n        for ( int k = 1 ; k <= 100 ; k++ ) {\n            BigInteger current = sterling2(100, k);\n            if ( current.compareTo(previous) > 0 ) {\n                previous = current;\n            }\n            else {\n                System.out.printf(\"%s%n(%d digits, k = %d)%n\", previous, previous.toString().length(), k-1);\n                break;\n            }\n        }\n    }\n    \n    private static Map<String,BigInteger> COMPUTED = new HashMap<>();\n    \n    private static final BigInteger sterling2(int n, int k) {\n        String key = n + \",\" + k;\n        if ( COMPUTED.containsKey(key) ) {\n            return COMPUTED.get(key);\n        }\n        if ( n == 0 && k == 0 ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {\n            return BigInteger.ZERO; \n        }\n        if ( n == k ) {\n            return BigInteger.valueOf(1);\n        }\n        if ( k > n ) {\n            return BigInteger.ZERO;\n        }\n        BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));\n        COMPUTED.put(key, result);\n        return result;\n    }\n\n}\n"}
{"id": 45282, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n"}
{"id": 45283, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n"}
{"id": 45284, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RecamanSequence {\n    public static void main(String[] args) {\n        List<Integer> a = new ArrayList<>();\n        a.add(0);\n\n        Set<Integer> used = new HashSet<>();\n        used.add(0);\n\n        Set<Integer> used1000 = new HashSet<>();\n        used1000.add(0);\n\n        boolean foundDup = false;\n        int n = 1;\n        while (n <= 15 || !foundDup || used1000.size() < 1001) {\n            int next = a.get(n - 1) - n;\n            if (next < 1 || used.contains(next)) {\n                next += 2 * n;\n            }\n            boolean alreadyUsed = used.contains(next);\n            a.add(next);\n            if (!alreadyUsed) {\n                used.add(next);\n                if (0 <= next && next <= 1000) {\n                    used1000.add(next);\n                }\n            }\n            if (n == 14) {\n                System.out.printf(\"The first 15 terms of the Recaman sequence are : %s\\n\", a);\n            }\n            if (!foundDup && alreadyUsed) {\n                System.out.printf(\"The first duplicate term is a[%d] = %d\\n\", n, next);\n                foundDup = true;\n            }\n            if (used1000.size() == 1001) {\n                System.out.printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n            }\n            n++;\n        }\n    }\n}\n"}
{"id": 45285, "name": "Memory allocation", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n", "Java": "\n\nObject foo = new Object(); \nint[] fooArray = new int[size]; \nint x = 0; \n"}
{"id": 45286, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n"}
{"id": 45287, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "Java": "public class Count{\n    public static void main(String[] args){\n        for(long i = 1; ;i++) System.out.println(i);\n    }\n}\n"}
{"id": 45288, "name": "Entropy_Narcissist", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n"}
{"id": 45289, "name": "Entropy_Narcissist", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n", "Java": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n    private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n    \n    public static void main(String[] args) {\n        System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n    }\n    \n    private static double getEntropy(String fileName) {\n        Map<Character,Integer> characterCount = new HashMap<>();\n        int length = 0;\n\n        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {        \n            int c = 0;\n            while ( (c = reader.read()) != -1 ) {\n                characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n                length++;\n            }\n        }\n        catch ( IOException e ) {\n            throw new RuntimeException(e);\n        }\n        \n        double entropy = 0;\n        for ( char key : characterCount.keySet() ) {\n            double fraction = (double) characterCount.get(key) / length;\n            entropy -= fraction * Math.log(fraction);\n        }\n\n        return entropy / Math.log(2);\n    }\n\n}\n"}
{"id": 45290, "name": "DNS query", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n", "Java": "import java.net.InetAddress;\nimport java.net.Inet4Address;\nimport java.net.Inet6Address;\nimport java.net.UnknownHostException;\n\nclass DnsQuery {\n    public static void main(String[] args) {\n        try {\n            InetAddress[] ipAddr = InetAddress.getAllByName(\"www.kame.net\");\n            for(int i=0; i < ipAddr.length ; i++) {\n                if (ipAddr[i] instanceof Inet4Address) {\n                    System.out.println(\"IPv4 : \" + ipAddr[i].getHostAddress());\n                } else if (ipAddr[i] instanceof Inet6Address) {\n                    System.out.println(\"IPv6 : \" + ipAddr[i].getHostAddress());\n                }\n            }\n        } catch (UnknownHostException uhe) {\n            System.err.println(\"unknown host\");\n        }\n    }\n}\n"}
{"id": 45291, "name": "Peano curve", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar points []gg.Point\n\nconst width = 81\n\nfunc peano(x, y, lg, i1, i2 int) {\n    if lg == 1 {\n        px := float64(width-x) * 10\n        py := float64(width-y) * 10\n        points = append(points, gg.Point{px, py})\n        return\n    }\n    lg /= 3\n    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)\n    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)\n    peano(x+lg, y+lg, lg, i1, 1-i2)\n    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)\n    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)\n    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)\n    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)\n    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)\n    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)\n}\n\nfunc main() {\n    peano(0, 0, width, 0, 0)\n    dc := gg.NewContext(820, 820)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for _, p := range points {\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetRGB(1, 0, 1) \n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"peano.png\")\n}\n", "Java": "import java.io.*;\n\npublic class PeanoCurve {\n    public static void main(final String[] args) {\n        try (Writer writer = new BufferedWriter(new FileWriter(\"peano_curve.svg\"))) {\n            PeanoCurve s = new PeanoCurve(writer);\n            final int length = 8;\n            s.currentAngle = 90;\n            s.currentX = length;\n            s.currentY = length;\n            s.lineLength = length;\n            s.begin(656);\n            s.execute(rewrite(4));\n            s.end();\n        } catch (final Exception ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private PeanoCurve(final Writer writer) {\n        this.writer = writer;\n    }\n\n    private void begin(final int size) throws IOException {\n        write(\"<svg xmlns='http:\n        write(\"<rect width='100%%' height='100%%' fill='white'/>\\n\");\n        write(\"<path stroke-width='1' stroke='black' fill='none' d='\");\n    }\n\n    private void end() throws IOException {\n        write(\"'/>\\n</svg>\\n\");\n    }\n\n    private void execute(final String s) throws IOException {\n        write(\"M%g,%g\\n\", currentX, currentY);\n        for (int i = 0, n = s.length(); i < n; ++i) {\n            switch (s.charAt(i)) {\n                case 'F':\n                    line(lineLength);\n                    break;\n                case '+':\n                    turn(ANGLE);\n                    break;\n                case '-':\n                    turn(-ANGLE);\n                    break;\n            }\n        }\n    }\n\n    private void line(final double length) throws IOException {\n        final double theta = (Math.PI * currentAngle) / 180.0;\n        currentX += length * Math.cos(theta);\n        currentY += length * Math.sin(theta);\n        write(\"L%g,%g\\n\", currentX, currentY);\n    }\n\n    private void turn(final int angle) {\n        currentAngle = (currentAngle + angle) % 360;\n    }\n\n    private void write(final String format, final Object... args) throws IOException {\n        writer.write(String.format(format, args));\n    }\n\n    private static String rewrite(final int order) {\n        String s = \"L\";\n        for (int i = 0; i < order; ++i) {\n            final StringBuilder sb = new StringBuilder();\n            for (int j = 0, n = s.length(); j < n; ++j) {\n                final char ch = s.charAt(j);\n                if (ch == 'L')\n                    sb.append(\"LFRFL-F-RFLFR+F+LFRFL\");\n                else if (ch == 'R')\n                    sb.append(\"RFLFR+F+LFRFL-F-RFLFR\");\n                else\n                    sb.append(ch);\n            }\n            s = sb.toString();\n        }\n        return s;\n    }\n\n    private final Writer writer;\n    private double lineLength;\n    private double currentX;\n    private double currentY;\n    private int currentAngle;\n    private static final int ANGLE = 90;\n}\n"}
{"id": 45292, "name": "Seven-sided dice from five-sided dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "Java": "import java.util.Random;\npublic class SevenSidedDice \n{\n\tprivate static final Random rnd = new Random();\n\tpublic static void main(String[] args)\n\t{\n\t\tSevenSidedDice now=new SevenSidedDice();\n\t\tSystem.out.println(\"Random number from 1 to 7: \"+now.seven());\n\t}\n\tint seven()\n\t{\n\t\tint v=21;\n\t\twhile(v>20)\n\t\t\tv=five()+five()*5-6;\n\t\treturn 1+v%7;\n\t}\n\tint five()\n\t{\n\t\treturn 1+rnd.nextInt(5);\n\t}\n}\n"}
{"id": 45293, "name": "Solve the no connection puzzle", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n", "Java": "import static java.lang.Math.abs;\nimport java.util.*;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\n\npublic class NoConnection {\n\n    \n    static int[][] links = {\n        {2, 3, 4}, \n        {3, 4, 5}, \n        {2, 4},    \n        {5},       \n        {2, 3, 4}, \n        {3, 4, 5}, \n    };\n\n    static int[] pegs = new int[8];\n\n    public static void main(String[] args) {\n\n        List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());\n        do {\n            Collections.shuffle(vals);\n            for (int i = 0; i < pegs.length; i++)\n                pegs[i] = vals.get(i);\n\n        } while (!solved());\n\n        printResult();\n    }\n\n    static boolean solved() {\n        for (int i = 0; i < links.length; i++)\n            for (int peg : links[i])\n                if (abs(pegs[i] - peg) == 1)\n                    return false;\n        return true;\n    }\n\n    static void printResult() {\n        System.out.printf(\"  %s %s%n\", pegs[0], pegs[1]);\n        System.out.printf(\"%s %s %s %s%n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n        System.out.printf(\"  %s %s%n\", pegs[6], pegs[7]);\n    }\n}\n"}
{"id": 45294, "name": "Magnanimous numbers", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class MagnanimousNumbers {\n\n    public static void main(String[] args) {\n        runTask(\"Find and display the first 45 magnanimous numbers.\", 1, 45);\n        runTask(\"241st through 250th magnanimous numbers.\", 241, 250);\n        runTask(\"391st through 400th magnanimous numbers.\", 391, 400);\n    }\n    \n    private static void runTask(String message, int startN, int endN) {\n        int count = 0;\n        List<Integer> nums = new ArrayList<>();\n        for ( int n = 0 ; count < endN ; n++ ) {\n            if ( isMagnanimous(n) ) {\n                nums.add(n);\n                count++;\n            }\n        }\n        System.out.printf(\"%s%n\", message);\n        System.out.printf(\"%s%n%n\", nums.subList(startN-1, endN));\n    }\n    \n    private static boolean isMagnanimous(long n) {\n        if ( n >= 0 && n <= 9 ) {\n            return true;\n        }\n        long q = 11;\n        for ( long div = 10 ; q >= 10 ; div *= 10 ) {\n            q = n / div;\n            long r = n % div;\n            if ( ! isPrime(q+r) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n"}
{"id": 45295, "name": "Magnanimous numbers", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class MagnanimousNumbers {\n\n    public static void main(String[] args) {\n        runTask(\"Find and display the first 45 magnanimous numbers.\", 1, 45);\n        runTask(\"241st through 250th magnanimous numbers.\", 241, 250);\n        runTask(\"391st through 400th magnanimous numbers.\", 391, 400);\n    }\n    \n    private static void runTask(String message, int startN, int endN) {\n        int count = 0;\n        List<Integer> nums = new ArrayList<>();\n        for ( int n = 0 ; count < endN ; n++ ) {\n            if ( isMagnanimous(n) ) {\n                nums.add(n);\n                count++;\n            }\n        }\n        System.out.printf(\"%s%n\", message);\n        System.out.printf(\"%s%n%n\", nums.subList(startN-1, endN));\n    }\n    \n    private static boolean isMagnanimous(long n) {\n        if ( n >= 0 && n <= 9 ) {\n            return true;\n        }\n        long q = 11;\n        for ( long div = 10 ; q >= 10 ; div *= 10 ) {\n            q = n / div;\n            long r = n % div;\n            if ( ! isPrime(q+r) ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    private static final int MAX = 100_000;\n    private static final boolean[] primes = new boolean[MAX];\n    private static boolean SIEVE_COMPLETE = false;\n    \n    private static final boolean isPrimeTrivial(long test) {\n        if ( ! SIEVE_COMPLETE ) {\n            sieve();\n            SIEVE_COMPLETE = true;\n        }\n        return primes[(int) test];\n    }\n    \n    private static final void sieve() {\n        \n        for ( int i = 2 ; i < MAX ; i++ ) {\n            primes[i] = true;            \n        }\n        for ( int i = 2 ; i < MAX ; i++ ) {\n            if ( primes[i] ) {\n                for ( int j = 2*i ; j < MAX ; j += i ) {\n                    primes[j] = false;\n                }\n            }\n        }\n    }\n\n    \n    public static final boolean isPrime(long testValue) {\n        if ( testValue == 2 ) return true;\n        if ( testValue % 2 == 0 ) return false;\n        if ( testValue <= MAX ) return isPrimeTrivial(testValue);\n        long d = testValue-1;\n        int s = 0;\n        while ( d % 2 == 0 ) {\n            s += 1;\n            d /= 2;\n        }\n        if ( testValue < 1373565L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 4759123141L ) {\n            if ( ! aSrp(2, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(7, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(61, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        if ( testValue < 10000000000000000L ) {\n            if ( ! aSrp(3, s, d, testValue) ) {\n                return false;\n            }\n            if ( ! aSrp(24251, s, d, testValue) ) {\n                return false;\n            }\n            return true;\n        }\n        \n        if ( ! aSrp(37, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(47, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(61, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(73, s, d, testValue) ) {\n            return false;\n        }\n        if ( ! aSrp(83, s, d, testValue) ) {\n            return false;\n        }\n        \n        return true;\n    }\n\n    private static final boolean aSrp(int a, int s, long d, long n) {\n        long modPow = modPow(a, d, n);\n        \n        if ( modPow == 1 ) {\n            return true;\n        }\n        int twoExpR = 1;\n        for ( int r = 0 ; r < s ; r++ ) {\n            if ( modPow(modPow, twoExpR, n) == n-1 ) {\n                return true;\n            }\n            twoExpR *= 2;\n        }\n        return false;\n    }\n    \n    private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);\n    \n    public static final long modPow(long base, long exponent, long modulus) {\n        long result = 1;\n        while ( exponent > 0 ) {\n            if ( exponent % 2 == 1 ) {\n                if ( result > SQRT || base > SQRT ) {\n                    result = multiply(result, base, modulus);\n                }\n                else {\n                    result = (result * base) % modulus;\n                }\n            }\n            exponent >>= 1;\n            if ( base > SQRT ) {\n                base = multiply(base, base, modulus);\n            }\n            else {\n                base = (base * base) % modulus;\n            }\n        }\n        return result;\n    }\n\n\n    \n    public static final long multiply(long a, long b, long modulus) {\n        long x = 0;\n        long y = a % modulus;\n        long t;\n        while ( b > 0 ) {\n            if ( b % 2 == 1 ) {\n                t = x + y;\n                x = (t > modulus ? t-modulus : t);\n            }\n            t = y << 1;\n            y = (t > modulus ? t-modulus : t);\n            b >>= 1;\n        }\n        return x % modulus;\n    }\n\n}\n"}
{"id": 45296, "name": "Extensible prime generator", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"fmt\"\n)\n\nfunc main() {\n    p := newP()\n    fmt.Print(\"First twenty: \")\n    for i := 0; i < 20; i++ {\n        fmt.Print(p(), \" \")\n    }\n    fmt.Print(\"\\nBetween 100 and 150: \")\n    n := p()\n    for n <= 100 {\n        n = p()\n    }\n    for ; n < 150; n = p() {\n        fmt.Print(n, \" \")\n    }\n    for n <= 7700 {\n        n = p()\n    }\n    c := 0\n    for ; n < 8000; n = p() {\n        c++\n    }\n    fmt.Println(\"\\nNumber beween 7,700 and 8,000:\", c)\n    p = newP()\n    for i := 1; i < 10000; i++ {\n        p()\n    }\n    fmt.Println(\"10,000th prime:\", p())\n}\n\nfunc newP() func() int {\n    n := 1\n    var pq pQueue\n    top := &pMult{2, 4, 0}\n    return func() int {\n        for {\n            n++\n            if n < top.pMult { \n                heap.Push(&pq, &pMult{prime: n, pMult: n * n})\n                top = pq[0]\n                return n\n            }\n            \n            for top.pMult == n {\n                top.pMult += top.prime\n                heap.Fix(&pq, 0)\n                top = pq[0]\n            }\n        }\n    }\n}\n\ntype pMult struct {\n    prime int\n    pMult int\n    index int\n}\n\ntype pQueue []*pMult\n\nfunc (q pQueue) Len() int           { return len(q) }\nfunc (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }\nfunc (q pQueue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n    q[i].index = i\n    q[j].index = j\n}\nfunc (p *pQueue) Push(x interface{}) {\n    q := *p\n    e := x.(*pMult)\n    e.index = len(q)\n    *p = append(q, e)\n}\nfunc (p *pQueue) Pop() interface{} {\n    q := *p\n    last := len(q) - 1\n    e := q[last]\n    *p = q[:last]\n    return e\n}\n", "Java": "import java.util.*;\n\npublic class PrimeGenerator {\n    private int limit_;\n    private int index_ = 0;\n    private int increment_;\n    private int count_ = 0;\n    private List<Integer> primes_ = new ArrayList<>();\n    private BitSet sieve_ = new BitSet();\n    private int sieveLimit_ = 0;\n\n    public PrimeGenerator(int initialLimit, int increment) {\n        limit_ = nextOddNumber(initialLimit);\n        increment_ = increment;\n        primes_.add(2);\n        findPrimes(3);\n    }\n\n    public int nextPrime() {\n        if (index_ == primes_.size()) {\n            if (Integer.MAX_VALUE - increment_ < limit_)\n                return 0;\n            int start = limit_ + 2;\n            limit_ = nextOddNumber(limit_ + increment_);\n            primes_.clear();\n            findPrimes(start);\n        }\n        ++count_;\n        return primes_.get(index_++);\n    }\n\n    public int count() {\n        return count_;\n    }\n\n    private void findPrimes(int start) {\n        index_ = 0;\n        int newLimit = sqrt(limit_);\n        for (int p = 3; p * p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p));\n            for (; q <= newLimit; q += 2*p)\n                sieve_.set(q/2 - 1, true);\n        }\n        sieveLimit_ = newLimit;\n        int count = (limit_ - start)/2 + 1;\n        BitSet composite = new BitSet(count);\n        for (int p = 3; p <= newLimit; p += 2) {\n            if (sieve_.get(p/2 - 1))\n                continue;\n            int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start;\n            q /= 2;\n            for (; q >= 0 && q < count; q += p)\n                composite.set(q, true);\n        }\n        for (int p = 0; p < count; ++p) {\n            if (!composite.get(p))\n                primes_.add(p * 2 + start);\n        }\n    }\n\n    private static int sqrt(int n) {\n        return nextOddNumber((int)Math.sqrt(n));\n    }\n\n    private static int nextOddNumber(int n) {\n        return 1 + 2 * (n/2);\n    }\n\n    public static void main(String[] args) {\n        PrimeGenerator pgen = new PrimeGenerator(20, 200000);\n        System.out.println(\"First 20 primes:\");\n        for (int i = 0; i < 20; ++i) {\n            if (i > 0)\n                System.out.print(\", \");\n            System.out.print(pgen.nextPrime());\n        }\n        System.out.println();\n        System.out.println(\"Primes between 100 and 150:\");\n        for (int i = 0; ; ) {\n            int prime = pgen.nextPrime();\n            if (prime > 150)\n                break;\n            if (prime >= 100) {\n                if (i++ != 0)\n                    System.out.print(\", \");\n                System.out.print(prime);\n            }\n        }\n        System.out.println();\n        int count = 0;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime > 8000)\n                break;\n            if (prime >= 7700)\n                ++count;\n        }\n        System.out.println(\"Number of primes between 7700 and 8000: \" + count);\n        int n = 10000;\n        for (;;) {\n            int prime = pgen.nextPrime();\n            if (prime == 0) {\n                System.out.println(\"Can't generate any more primes.\");\n                break;\n            }\n            if (pgen.count() == n) {\n                System.out.println(n + \"th prime: \" + prime);\n                n *= 10;\n            }\n        }\n    }\n}\n"}
{"id": 45297, "name": "Rock-paper-scissors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n", "Java": "import java.util.Arrays;\nimport java.util.EnumMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.Random;\n\npublic class RPS {\n\tpublic enum Item{\n\t\tROCK, PAPER, SCISSORS, ;\n\t\tpublic List<Item> losesToList;\n\t\tpublic boolean losesTo(Item other) {\n\t\t\treturn losesToList.contains(other);\n\t\t}\n\t\tstatic {\n\t\t\tSCISSORS.losesToList = Arrays.asList(ROCK);\n\t\t\tROCK.losesToList = Arrays.asList(PAPER);\n\t\t\tPAPER.losesToList = Arrays.asList(SCISSORS);\n\t\t\t\n                }\n\t}\n\t\n\tpublic final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{\n\t\tfor(Item item:Item.values())\n\t\t\tput(item, 1);\n\t}};\n\n\tprivate int totalThrows = Item.values().length;\n\n\tpublic static void main(String[] args){\n\t\tRPS rps = new RPS();\n\t\trps.run();\n\t}\n\n\tpublic void run() {\n\t\tScanner in = new Scanner(System.in);\n\t\tSystem.out.print(\"Make your choice: \");\n\t\twhile(in.hasNextLine()){\n\t\t\tItem aiChoice = getAIChoice();\n\t\t\tString input = in.nextLine();\n\t\t\tItem choice;\n\t\t\ttry{\n\t\t\t\tchoice = Item.valueOf(input.toUpperCase());\n\t\t\t}catch (IllegalArgumentException ex){\n\t\t\t\tSystem.out.println(\"Invalid choice\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcounts.put(choice, counts.get(choice) + 1);\n\t\t\ttotalThrows++;\n\t\t\tSystem.out.println(\"Computer chose: \" + aiChoice);\n\t\t\tif(aiChoice == choice){\n\t\t\t\tSystem.out.println(\"Tie!\");\n\t\t\t}else if(aiChoice.losesTo(choice)){\n\t\t\t\tSystem.out.println(\"You chose...wisely. You win!\");\n\t\t\t}else{\n\t\t\t\tSystem.out.println(\"You chose...poorly. You lose!\");\n\t\t\t}\n\t\t\tSystem.out.print(\"Make your choice: \");\n\t\t}\n\t}\n\n\tprivate static final Random rng = new Random();\n\tprivate Item getAIChoice() {\n\t\tint rand = rng.nextInt(totalThrows);\n\t\tfor(Map.Entry<Item, Integer> entry:counts.entrySet()){\n\t\t\tItem item = entry.getKey();\n\t\t\tint count = entry.getValue();\n\t\t\tif(rand < count){\n\t\t\t\tList<Item> losesTo = item.losesToList;\n\t\t\t\treturn losesTo.get(rng.nextInt(losesTo.size()));\n\t\t\t}\n\t\t\trand -= count;\n\t\t}\n\t\treturn null;\n\t}\n}\n"}
{"id": 45298, "name": "Create a two-dimensional array at runtime", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n", "Java": "import java.util.Scanner;\n\npublic class twoDimArray {\n  public static void main(String[] args) {\n        Scanner in = new Scanner(System.in);\n        \n        int nbr1 = in.nextInt();\n        int nbr2 = in.nextInt();\n        \n        double[][] array = new double[nbr1][nbr2];\n        array[0][0] = 42.0;\n        System.out.println(\"The number at place [0 0] is \" + array[0][0]);\n  }\n}\n"}
{"id": 45299, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n"}
{"id": 45300, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "Java": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n    public static int chineseRemainder(int[] n, int[] a) {\n\n        int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n        int p, sm = 0;\n        for (int i = 0; i < n.length; i++) {\n            p = prod / n[i];\n            sm += a[i] * mulInv(p, n[i]) * p;\n        }\n        return sm % prod;\n    }\n\n    private static int mulInv(int a, int b) {\n        int b0 = b;\n        int x0 = 0;\n        int x1 = 1;\n\n        if (b == 1)\n            return 1;\n\n        while (a > 1) {\n            int q = a / b;\n            int amb = a % b;\n            a = b;\n            b = amb;\n            int xqx = x1 - q * x0;\n            x1 = x0;\n            x0 = xqx;\n        }\n\n        if (x1 < 0)\n            x1 += b0;\n\n        return x1;\n    }\n\n    public static void main(String[] args) {\n        int[] n = {3, 5, 7};\n        int[] a = {2, 3, 2};\n        System.out.println(chineseRemainder(n, a));\n    }\n}\n"}
{"id": 45301, "name": "Vigenère cipher_Cryptanalysis", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar encoded = \n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [26]float64{\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n}\n\nfunc sum(a []float64) (sum float64) {\n    for _, f := range a {\n        sum += f\n    }\n    return\n}\n\nfunc bestMatch(a []float64) int {\n    sum := sum(a)\n    bestFit, bestRotate := 1e100, 0\n    for rotate := 0; rotate < 26; rotate++ {\n        fit := 0.0\n        for i := 0; i < 26; i++ {\n            d := a[(i+rotate)%26]/sum - freq[i]\n            fit += d * d / freq[i]\n        }\n        if fit < bestFit {\n            bestFit, bestRotate = fit, rotate\n        }\n    }\n    return bestRotate\n}\n\nfunc freqEveryNth(msg []int, key []byte) float64 {\n    l := len(msg)\n    interval := len(key)\n    out := make([]float64, 26)\n    accu := make([]float64, 26)\n    for j := 0; j < interval; j++ {\n        for k := 0; k < 26; k++ {\n            out[k] = 0.0\n        }\n        for i := j; i < l; i += interval {\n            out[msg[i]]++\n        }\n        rot := bestMatch(out)\n        key[j] = byte(rot + 65)\n        for i := 0; i < 26; i++ {\n            accu[i] += out[(i+rot)%26]\n        }\n    }\n    sum := sum(accu)\n    ret := 0.0\n    for i := 0; i < 26; i++ {\n        d := accu[i]/sum - freq[i]\n        ret += d * d / freq[i]\n    }\n    return ret\n}\n\nfunc decrypt(text, key string) string {\n    var sb strings.Builder\n    ki := 0\n    for _, c := range text {\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        ci := (c - rune(key[ki]) + 26) % 26\n        sb.WriteRune(ci + 65)\n        ki = (ki + 1) % len(key)\n    }\n    return sb.String()\n}\n\nfunc main() {\n    enc := strings.Replace(encoded, \" \", \"\", -1)\n    txt := make([]int, len(enc))\n    for i := 0; i < len(txt); i++ {\n        txt[i] = int(enc[i] - 'A')\n    }\n    bestFit, bestKey := 1e100, \"\"\n    fmt.Println(\"  Fit     Length   Key\")\n    for j := 1; j <= 26; j++ {\n        key := make([]byte, j)\n        fit := freqEveryNth(txt, key)\n        sKey := string(key)\n        fmt.Printf(\"%f    %2d     %s\", fit, j, sKey)\n        if fit < bestFit {\n            bestFit, bestKey = fit, sKey\n            fmt.Print(\" <--- best so far\")\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nBest key :\", bestKey)\n    fmt.Printf(\"\\nDecrypted text:\\n%s\\n\", decrypt(enc, bestKey))\n}\n", "Java": "public class Vig{\nstatic String encodedMessage =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n \nfinal static double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n \n\npublic static void main(String[] args) {\n    int lenghtOfEncodedMessage = encodedMessage.length();\n    char[] encoded = new char [lenghtOfEncodedMessage] ;\n    char[] key =  new char [lenghtOfEncodedMessage] ;\n\n    encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0);\n    int txt[] = new int[lenghtOfEncodedMessage];\n    int len = 0, j;\n\n    double fit, best_fit = 1e100;\n \n    for (j = 0; j < lenghtOfEncodedMessage; j++)\n        if (Character.isUpperCase(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n \n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        System.out.printf(\"%f, key length: %2d \", fit, j);\n            System.out.print(key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            System.out.print(\" <--- best so far\");\n        }\n        System.out.print(\"\\n\");\n\n    }\n}\n\n\n    static String decrypt(String text, final String key) {\n        String res = \"\";\n        text = text.toUpperCase();\n        for (int i = 0, j = 0; i < text.length(); i++) {\n            char c = text.charAt(i);\n            if (c < 'A' || c > 'Z') continue;\n            res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n            j = ++j % key.length();\n        }\n        return res;\n    }\n\nstatic int best_match(final double []a, final double []b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n \n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n \n    return best_rotate;\n}\n \nstatic double freq_every_nth(final int []msg, int len, int interval, char[] key) {\n    double sum, d, ret;\n    double  [] accu = new double [26];\n    double  [] out = new double [26];\n    int i, j, rot;\n \n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n\trot = best_match(out, freq);\n\ttry{\n            key[j] = (char)(rot + 'A');\n\t} catch (Exception e) {\n\t\tSystem.out.print(e.getMessage());\n\t}\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n \n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n \n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n \n    key[interval] = '\\0';\n    return ret;\n}\n \n}\n"}
{"id": 45302, "name": "Pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n", "Java": "import java.math.BigInteger ;\n\npublic class Pi {\n  final BigInteger TWO = BigInteger.valueOf(2) ;\n  final BigInteger THREE = BigInteger.valueOf(3) ;\n  final BigInteger FOUR = BigInteger.valueOf(4) ;\n  final BigInteger SEVEN = BigInteger.valueOf(7) ;\n\n  BigInteger q = BigInteger.ONE ;\n  BigInteger r = BigInteger.ZERO ;\n  BigInteger t = BigInteger.ONE ;\n  BigInteger k = BigInteger.ONE ;\n  BigInteger n = BigInteger.valueOf(3) ;\n  BigInteger l = BigInteger.valueOf(3) ;\n\n  public void calcPiDigits(){\n    BigInteger nn, nr ;\n    boolean first = true ;\n    while(true){\n        if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){\n          System.out.print(n) ;\n          if(first){System.out.print(\".\") ; first = false ;}\n          nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ;\n          n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ;\n          q = q.multiply(BigInteger.TEN) ;\n          r = nr ;\n          System.out.flush() ;\n        }else{\n          nr = TWO.multiply(q).add(r).multiply(l) ;\n          nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ;\n          q = q.multiply(k) ;\n          t = t.multiply(l) ;\n          l = l.add(TWO) ;\n          k = k.add(BigInteger.ONE) ;\n          n = nn ;\n          r = nr ;\n        }\n    }\n  }\n\n  public static void main(String[] args) {\n    Pi p = new Pi() ;\n    p.calcPiDigits() ;\n  }\n}\n"}
{"id": 45303, "name": "Hofstadter Q sequence", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n"}
{"id": 45304, "name": "Hofstadter Q sequence", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class HofQ {\n\tprivate static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{\n\t\tput(1, 1);\n\t\tput(2, 1);\n\t}};\n\t\n\tprivate static int[] nUses = new int[100001];\n\t\n\tpublic static int Q(int n){\n\t\tnUses[n]++;\n\t\tif(q.containsKey(n)){\n\t\t\treturn q.get(n);\n\t\t}\n\t\tint ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));\n\t\tq.put(n, ans);\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 1; i <= 10; i++){\n\t\t\tSystem.out.println(\"Q(\" + i + \") = \" + Q(i));\n\t\t}\n\t\tint last = 6;\n\t\tint count = 0;\n\t\tfor(int i = 11; i <= 100000; i++){\n\t\t\tint curr = Q(i);\n\t\t\tif(curr < last) count++;\n\t\t\tlast = curr;\n\t\t\tif(i == 1000) System.out.println(\"Q(1000) = \" + curr);\n\t\t}\n\t\tSystem.out.println(\"Q(i) is less than Q(i-1) for i <= 100000 \" + count + \" times\");\n\t\t\n\t\t\n\t\tint maxUses = 0, maxN = 0;\n\t\tfor(int i = 1; i<nUses.length;i++){\n\t\t\tif(nUses[i] > maxUses){\n\t\t\t\tmaxUses = nUses[i];\n\t\t\t\tmaxN = i;\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Q(\" + maxN + \") was called the most with \" + maxUses + \" calls\");\n\t}\n}\n"}
{"id": 45305, "name": "Y combinator", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n", "Java": "import java.util.function.Function;\n\npublic interface YCombinator {\n  interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }\n  public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {\n    RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));\n    return r.apply(r);\n  }\n\n  public static void main(String... arguments) {\n    Function<Integer,Integer> fib = Y(f -> n ->\n      (n <= 2)\n        ? 1\n        : (f.apply(n - 1) + f.apply(n - 2))\n    );\n    Function<Integer,Integer> fac = Y(f -> n ->\n      (n <= 1)\n        ? 1\n        : (n * f.apply(n - 1))\n    );\n\n    System.out.println(\"fib(10) = \" + fib.apply(10));\n    System.out.println(\"fac(10) = \" + fac.apply(10));\n  }\n}\n"}
{"id": 45306, "name": "Y combinator", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n", "Java": "import java.util.function.Function;\n\npublic interface YCombinator {\n  interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }\n  public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {\n    RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));\n    return r.apply(r);\n  }\n\n  public static void main(String... arguments) {\n    Function<Integer,Integer> fib = Y(f -> n ->\n      (n <= 2)\n        ? 1\n        : (f.apply(n - 1) + f.apply(n - 2))\n    );\n    Function<Integer,Integer> fac = Y(f -> n ->\n      (n <= 1)\n        ? 1\n        : (n * f.apply(n - 1))\n    );\n\n    System.out.println(\"fib(10) = \" + fib.apply(10));\n    System.out.println(\"fac(10) = \" + fac.apply(10));\n  }\n}\n"}
{"id": 45307, "name": "Return multiple values", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n", "Java": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\n\npublic class RReturnMultipleVals {\n  public static final String K_lipsum = \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n  public static final Long   K_1024   = 1024L;\n  public static final String L        = \"L\";\n  public static final String R        = \"R\";\n\n  \n  public static void main(String[] args) throws NumberFormatException{\n    Long nv_;\n    String sv_;\n    switch (args.length) {\n      case 0:\n        nv_ = K_1024;\n        sv_ = K_lipsum;\n        break;\n      case 1:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = K_lipsum;\n        break;\n      case 2:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        break;\n      default:\n        nv_ = Long.parseLong(args[0]);\n        sv_ = args[1];\n        for (int ix = 2; ix < args.length; ++ix) {\n          sv_ = sv_ + \" \" + args[ix];\n        }\n        break;\n    }\n\n    RReturnMultipleVals lcl = new RReturnMultipleVals();\n\n    Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); \n    System.out.println(\"Results extracted from a composite object:\");\n    System.out.printf(\"%s, %s%n%n\", rvp.getLeftVal(), rvp.getRightVal());\n\n    List<Object> rvl = lcl.getPairFromList(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"List\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvl.get(0), rvl.get(1));\n\n    Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); \n    System.out.println(\"Results extracted from a Java Colections \\\"Map\\\" object:\");\n    System.out.printf(\"%s, %s%n%n\", rvm.get(L), rvm.get(R));\n  }\n  \n  \n  \n  public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {\n    return new Pair<T, U>(vl_, vr_);\n  }\n  \n  \n  \n  public List<Object> getPairFromList(Object nv_, Object sv_) {\n    List<Object> rset = new ArrayList<Object>();\n    rset.add(nv_);\n    rset.add(sv_);\n    return rset;\n  }\n  \n  \n  \n  public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {\n    Map<String, Object> rset = new HashMap<String, Object>();\n    rset.put(L, nv_);\n    rset.put(R, sv_);\n    return rset;\n  }\n\n  \n  private static class Pair<L, R> {\n    private L leftVal;\n    private R rightVal;\n\n    public Pair(L nv_, R sv_) {\n      setLeftVal(nv_);\n      setRightVal(sv_);\n    }\n    public void setLeftVal(L nv_) {\n      leftVal = nv_;\n    }\n    public L getLeftVal() {\n      return leftVal;\n    }\n    public void setRightVal(R sv_) {\n      rightVal = sv_;\n    }\n    public R getRightVal() {\n      return rightVal;\n    }\n  }\n}\n"}
{"id": 45308, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n"}
{"id": 45309, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class VanEckSequence {\n\n    public static void main(String[] args) {\n        System.out.println(\"First 10 terms of Van Eck's sequence:\");\n        vanEck(1, 10);\n        System.out.println(\"\");\n        System.out.println(\"Terms 991 to 1000 of Van Eck's sequence:\");\n        vanEck(991, 1000);\n    }\n    \n    private static void vanEck(int firstIndex, int lastIndex) {\n        Map<Integer,Integer> vanEckMap = new HashMap<>();        \n        int last = 0;\n        if ( firstIndex == 1 ) {\n            System.out.printf(\"VanEck[%d] = %d%n\", 1, 0);\n        }\n        for ( int n = 2 ; n <= lastIndex ; n++ ) {\n            int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;\n            vanEckMap.put(last, n);\n            last = vanEck;\n            if ( n >= firstIndex ) {\n                System.out.printf(\"VanEck[%d] = %d%n\", n, vanEck);\n            }\n        }\n        \n    }\n\n}\n"}
{"id": 45310, "name": "FTP", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport org.apache.commons.net.ftp.FTP;\nimport org.apache.commons.net.ftp.FTPClient;\nimport org.apache.commons.net.ftp.FTPFile;\nimport org.apache.commons.net.ftp.FTPReply;\n\npublic class FTPconn {\n\n    public static void main(String[] args) throws IOException {\n        String server = \"ftp.hq.nasa.gov\";\n        int port = 21;\n        String user = \"anonymous\";\n        String pass = \"ftptest@example.com\";\n\n        OutputStream output = null;\n\n        FTPClient ftpClient = new FTPClient();\n        try {\n            ftpClient.connect(server, port);\n\n            serverReply(ftpClient);\n\n            int replyCode = ftpClient.getReplyCode();\n            if (!FTPReply.isPositiveCompletion(replyCode)) {\n                System.out.println(\"Failure. Server reply code: \" + replyCode);\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            if (!ftpClient.login(user, pass)) {\n                System.out.println(\"Could not login to the server.\");\n                return;\n            }\n\n            String dir = \"pub/issoutreach/Living in Space Stories (MP3 Files)/\";\n            if (!ftpClient.changeWorkingDirectory(dir)) {\n                System.out.println(\"Change directory failed.\");\n                return;\n            }\n\n            ftpClient.enterLocalPassiveMode();\n\n            for (FTPFile file : ftpClient.listFiles())\n                System.out.println(file);\n\n            String filename = \"Can People go to Mars.mp3\";\n            output = new FileOutputStream(filename);\n\n            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);\n            if (!ftpClient.retrieveFile(filename, output)) {\n                System.out.println(\"Retrieving file failed\");\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            ftpClient.logout();\n\n        } finally {\n            if (output != null)\n                output.close();\n        }\n    }\n\n    private static void serverReply(FTPClient ftpClient) {\n        for (String reply : ftpClient.getReplyStrings()) {\n            System.out.println(reply);\n        }\n    }\n}\n"}
{"id": 45311, "name": "FTP", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n", "Java": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport org.apache.commons.net.ftp.FTP;\nimport org.apache.commons.net.ftp.FTPClient;\nimport org.apache.commons.net.ftp.FTPFile;\nimport org.apache.commons.net.ftp.FTPReply;\n\npublic class FTPconn {\n\n    public static void main(String[] args) throws IOException {\n        String server = \"ftp.hq.nasa.gov\";\n        int port = 21;\n        String user = \"anonymous\";\n        String pass = \"ftptest@example.com\";\n\n        OutputStream output = null;\n\n        FTPClient ftpClient = new FTPClient();\n        try {\n            ftpClient.connect(server, port);\n\n            serverReply(ftpClient);\n\n            int replyCode = ftpClient.getReplyCode();\n            if (!FTPReply.isPositiveCompletion(replyCode)) {\n                System.out.println(\"Failure. Server reply code: \" + replyCode);\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            if (!ftpClient.login(user, pass)) {\n                System.out.println(\"Could not login to the server.\");\n                return;\n            }\n\n            String dir = \"pub/issoutreach/Living in Space Stories (MP3 Files)/\";\n            if (!ftpClient.changeWorkingDirectory(dir)) {\n                System.out.println(\"Change directory failed.\");\n                return;\n            }\n\n            ftpClient.enterLocalPassiveMode();\n\n            for (FTPFile file : ftpClient.listFiles())\n                System.out.println(file);\n\n            String filename = \"Can People go to Mars.mp3\";\n            output = new FileOutputStream(filename);\n\n            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);\n            if (!ftpClient.retrieveFile(filename, output)) {\n                System.out.println(\"Retrieving file failed\");\n                return;\n            }\n\n            serverReply(ftpClient);\n\n            ftpClient.logout();\n\n        } finally {\n            if (output != null)\n                output.close();\n        }\n    }\n\n    private static void serverReply(FTPClient ftpClient) {\n        for (String reply : ftpClient.getReplyStrings()) {\n            System.out.println(reply);\n        }\n    }\n}\n"}
{"id": 45312, "name": "24 game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n", "Java": "import java.util.*;\n\npublic class Game24 {\n    static Random r = new Random();\n\n    public static void main(String[] args) {\n\n        int[] digits = randomDigits();\n        Scanner in = new Scanner(System.in);\n\n        System.out.print(\"Make 24 using these digits: \");\n        System.out.println(Arrays.toString(digits));\n        System.out.print(\"> \");\n\n        Stack<Float> s = new Stack<>();\n        long total = 0;\n        for (char c : in.nextLine().toCharArray()) {\n            if ('0' <= c && c <= '9') {\n                int d = c - '0';\n                total += (1 << (d * 5));\n                s.push((float) d);\n            } else if (\"+/-*\".indexOf(c) != -1) {\n                s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        }\n        if (tallyDigits(digits) != total)\n            System.out.print(\"Not the same digits. \");\n        else if (Math.abs(24 - s.peek()) < 0.001F)\n            System.out.println(\"Correct!\");\n        else\n            System.out.print(\"Not correct.\");\n    }\n\n    static float applyOperator(float a, float b, char c) {\n        switch (c) {\n            case '+':\n                return a + b;\n            case '-':\n                return b - a;\n            case '*':\n                return a * b;\n            case '/':\n                return b / a;\n            default:\n                return Float.NaN;\n        }\n    }\n\n    static long tallyDigits(int[] a) {\n        long total = 0;\n        for (int i = 0; i < 4; i++)\n            total += (1 << (a[i] * 5));\n        return total;\n    }\n\n    static int[] randomDigits() {        \n        int[] result = new int[4];\n        for (int i = 0; i < 4; i++)\n            result[i] = r.nextInt(9) + 1;\n        return result;\n    }\n}\n"}
{"id": 45313, "name": "24 game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n", "Java": "import java.util.*;\n\npublic class Game24 {\n    static Random r = new Random();\n\n    public static void main(String[] args) {\n\n        int[] digits = randomDigits();\n        Scanner in = new Scanner(System.in);\n\n        System.out.print(\"Make 24 using these digits: \");\n        System.out.println(Arrays.toString(digits));\n        System.out.print(\"> \");\n\n        Stack<Float> s = new Stack<>();\n        long total = 0;\n        for (char c : in.nextLine().toCharArray()) {\n            if ('0' <= c && c <= '9') {\n                int d = c - '0';\n                total += (1 << (d * 5));\n                s.push((float) d);\n            } else if (\"+/-*\".indexOf(c) != -1) {\n                s.push(applyOperator(s.pop(), s.pop(), c));\n            }\n        }\n        if (tallyDigits(digits) != total)\n            System.out.print(\"Not the same digits. \");\n        else if (Math.abs(24 - s.peek()) < 0.001F)\n            System.out.println(\"Correct!\");\n        else\n            System.out.print(\"Not correct.\");\n    }\n\n    static float applyOperator(float a, float b, char c) {\n        switch (c) {\n            case '+':\n                return a + b;\n            case '-':\n                return b - a;\n            case '*':\n                return a * b;\n            case '/':\n                return b / a;\n            default:\n                return Float.NaN;\n        }\n    }\n\n    static long tallyDigits(int[] a) {\n        long total = 0;\n        for (int i = 0; i < 4; i++)\n            total += (1 << (a[i] * 5));\n        return total;\n    }\n\n    static int[] randomDigits() {        \n        int[] result = new int[4];\n        for (int i = 0; i < 4; i++)\n            result[i] = r.nextInt(9) + 1;\n        return result;\n    }\n}\n"}
{"id": 45314, "name": "Loops_Continue", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 10; i++ {\n        fmt.Printf(\"%d\", i)\n        if i%5 == 0 {\n            fmt.Printf(\"\\n\")\n            continue\n        }\n        fmt.Printf(\", \")\n    }\n}\n", "Java": "for(int i = 1;i <= 10; i++){\n   System.out.print(i);\n   if(i % 5 == 0){\n      System.out.println();\n      continue;\n   }\n   System.out.print(\", \");\n}\n"}
{"id": 45315, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\n\npublic class ColorFrame extends JFrame {\n\tpublic ColorFrame(int width, int height) {\n\t\tthis.setDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tthis.setSize(width, height);\n\t\tthis.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tColor[] colors = { Color.black, Color.red, Color.green, Color.blue,\n\t\t\t\tColor.pink, Color.CYAN, Color.yellow, Color.white };\n\n\t\tfor (int i = 0; i < colors.length; i++) {\n\t\t\tg.setColor(colors[i]);\n\t\t\tg.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()\n\t\t\t\t\t/ colors.length, this.getHeight());\n\t\t}\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tnew ColorFrame(200, 200);\n\t}\n}\n"}
{"id": 45316, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\n\npublic class ColorFrame extends JFrame {\n\tpublic ColorFrame(int width, int height) {\n\t\tthis.setDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tthis.setSize(width, height);\n\t\tthis.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tColor[] colors = { Color.black, Color.red, Color.green, Color.blue,\n\t\t\t\tColor.pink, Color.CYAN, Color.yellow, Color.white };\n\n\t\tfor (int i = 0; i < colors.length; i++) {\n\t\t\tg.setColor(colors[i]);\n\t\t\tg.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()\n\t\t\t\t\t/ colors.length, this.getHeight());\n\t\t}\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tnew ColorFrame(200, 200);\n\t}\n}\n"}
{"id": 45317, "name": "LU decomposition", "Go": "package main\n\nimport \"fmt\"\n    \ntype matrix [][]float64\n\nfunc zero(n int) matrix {\n    r := make([][]float64, n)\n    a := make([]float64, n*n)\n    for i := range r {\n        r[i] = a[n*i : n*(i+1)]\n    } \n    return r \n}\n    \nfunc eye(n int) matrix {\n    r := zero(n)\n    for i := range r {\n        r[i][i] = 1\n    }\n    return r\n}   \n    \nfunc (m matrix) print(label string) {\n    if label > \"\" {\n        fmt.Printf(\"%s:\\n\", label)\n    }\n    for _, r := range m {\n        for _, e := range r {\n            fmt.Printf(\" %9.5f\", e)\n        }\n        fmt.Println()\n    }\n}\n\nfunc (a matrix) pivotize() matrix { \n    p := eye(len(a))\n    for j, r := range a {\n        max := r[j] \n        row := j\n        for i := j; i < len(a); i++ {\n            if a[i][j] > max {\n                max = a[i][j]\n                row = i\n            }\n        }\n        if j != row {\n            \n            p[j], p[row] = p[row], p[j]\n        }\n    } \n    return p\n}\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    r := zero(len(m1))\n    for i, r1 := range m1 {\n        for j := range m2 {\n            for k := range m1 {\n                r[i][j] += r1[k] * m2[k][j]\n            }\n        }\n    }\n    return r\n}\n\nfunc (a matrix) lu() (l, u, p matrix) {\n    l = zero(len(a))\n    u = zero(len(a))\n    p = a.pivotize()\n    a = p.mul(a)\n    for j := range a {\n        l[j][j] = 1\n        for i := 0; i <= j; i++ {\n            sum := 0.\n            for k := 0; k < i; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            u[i][j] = a[i][j] - sum\n        }\n        for i := j; i < len(a); i++ {\n            sum := 0.\n            for k := 0; k < j; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            l[i][j] = (a[i][j] - sum) / u[j][j]\n        }\n    }\n    return\n}\n\nfunc main() {\n    showLU(matrix{\n        {1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}})\n    showLU(matrix{\n        {11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}})\n}\n\nfunc showLU(a matrix) {\n    a.print(\"\\na\")\n    l, u, p := a.lu()\n    l.print(\"l\")\n    u.print(\"u\") \n    p.print(\"p\") \n}\n", "Java": "import static java.util.Arrays.stream;\nimport java.util.Locale;\nimport static java.util.stream.IntStream.range;\n\npublic class Test {\n\n    static double dotProduct(double[] a, double[] b) {\n        return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum();\n    }\n\n    static double[][] matrixMul(double[][] A, double[][] B) {\n        double[][] result = new double[A.length][B[0].length];\n        double[] aux = new double[B.length];\n\n        for (int j = 0; j < B[0].length; j++) {\n\n            for (int k = 0; k < B.length; k++)\n                aux[k] = B[k][j];\n\n            for (int i = 0; i < A.length; i++)\n                result[i][j] = dotProduct(A[i], aux);\n        }\n        return result;\n    }\n\n    static double[][] pivotize(double[][] m) {\n        int n = m.length;\n        double[][] id = range(0, n).mapToObj(j -> range(0, n)\n                .mapToDouble(i -> i == j ? 1 : 0).toArray())\n                .toArray(double[][]::new);\n\n        for (int i = 0; i < n; i++) {\n            double maxm = m[i][i];\n            int row = i;\n            for (int j = i; j < n; j++)\n                if (m[j][i] > maxm) {\n                    maxm = m[j][i];\n                    row = j;\n                }\n\n            if (i != row) {\n                double[] tmp = id[i];\n                id[i] = id[row];\n                id[row] = tmp;\n            }\n        }\n        return id;\n    }\n\n    static double[][][] lu(double[][] A) {\n        int n = A.length;\n        double[][] L = new double[n][n];\n        double[][] U = new double[n][n];\n        double[][] P = pivotize(A);\n        double[][] A2 = matrixMul(P, A);\n\n        for (int j = 0; j < n; j++) {\n            L[j][j] = 1;\n            for (int i = 0; i < j + 1; i++) {\n                double s1 = 0;\n                for (int k = 0; k < i; k++)\n                    s1 += U[k][j] * L[i][k];\n                U[i][j] = A2[i][j] - s1;\n            }\n            for (int i = j; i < n; i++) {\n                double s2 = 0;\n                for (int k = 0; k < j; k++)\n                    s2 += U[k][j] * L[i][k];\n                L[i][j] = (A2[i][j] - s2) / U[j][j];\n            }\n        }\n        return new double[][][]{L, U, P};\n    }\n\n    static void print(double[][] m) {\n        stream(m).forEach(a -> {\n            stream(a).forEach(n -> System.out.printf(Locale.US, \"%5.1f \", n));\n            System.out.println();\n        });\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}};\n\n        double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1},\n        {2.0, 5, 7, 1}};\n\n        for (double[][] m : lu(a))\n            print(m);\n\n        System.out.println();\n\n        for (double[][] m : lu(b))\n            print(m);\n    }\n}\n"}
{"id": 45318, "name": "General FizzBuzz", "Go": "package main\n\nimport (\n\t\"fmt\"\n)\n\nconst numbers = 3\n\nfunc main() {\n\n\t\n\tmax := 20\n\twords := map[int]string{\n\t\t3: \"Fizz\",\n\t\t5: \"Buzz\",\n\t\t7: \"Baxx\",\n\t}\n\tkeys := []int{3, 5, 7}\n\tdivisible := false\n\tfor i := 1; i <= max; i++ {\n\t\tfor _, n := range keys {\n\t\t\tif i % n == 0 {\n\t\t\t\tfmt.Print(words[n])\n\t\t\t\tdivisible = true\n\t\t\t}\n\t\t}\n\t\tif !divisible {\n\t\t\tfmt.Print(i)\n\t\t}\n\t\tfmt.Println()\n\t\tdivisible = false\n\t}\n\n}\n", "Java": "public class FizzBuzz {\n\n    public static void main(String[] args) {\n        Sound[] sounds = {new Sound(3, \"Fizz\"), new Sound(5, \"Buzz\"),  new Sound(7, \"Baxx\")};\n        for (int i = 1; i <= 20; i++) {\n            StringBuilder sb = new StringBuilder();\n            for (Sound sound : sounds) {\n                sb.append(sound.generate(i));\n            }\n            System.out.println(sb.length() == 0 ? i : sb.toString());\n        }\n    }\n\n    private static class Sound {\n        private final int trigger;\n        private final String onomatopoeia;\n\n        public Sound(int trigger, String onomatopoeia) {\n            this.trigger = trigger;\n            this.onomatopoeia = onomatopoeia;\n        }\n\n        public String generate(int i) {\n            return i % trigger == 0 ? onomatopoeia : \"\";\n        }\n\n    }\n\n}\n"}
{"id": 45319, "name": "Bitwise operations", "Python": "def bitwise_built_ins(width, a, b):\n    mask = (1 << width) - 1\n    print(f)\n\ndef rotr(width, a, n):\n    \"Rotate a, n times to the right\"\n    if n < 0:\n        return rotl(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return ((a >> n)    \n                | ((a & ((1 << n) - 1))   \n                   << (width - n)))  \n\ndef rotl(width, a, n):\n    \"Rotate a, n times to the left\"\n    if n < 0:\n        return rotr(width, a, -n)\n    elif n == 0:\n        return a\n    else:\n        mask = (1 << width) - 1\n        a, n = a & mask, n % width\n        return (((a << n) & mask)      \n                | (a >> (width - n)))  \n    \ndef asr(width, a, n):\n    \"Arithmetic shift a, n times to the right. (sign preserving).\"\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    if n < 0:\n        return  (a << -n) & mask\n    elif n == 0:\n        return a\n    elif n >= width:\n        return mask if a & top_bit_mask else 0\n    else:\n        a = a & mask\n        if a & top_bit_mask:    \n            signs = (1 << n) - 1\n            return a >> n | (signs << width - n)\n        else:\n            return a >> n\n    \n      \ndef helper_funcs(width, a):\n    mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)\n    aa = a | top_bit_mask  \n    print(f)\n\nif __name__ == '__main__':\n    bitwise_built_ins(8, 27, 125)\n    helper_funcs(8, 27)\n", "C#": "static void bitwise(int a, int b)\n        {\n            Console.WriteLine(\"a and b is {0}\", a & b);\n            Console.WriteLine(\"a or b is {0}\", a | b);\n            Console.WriteLine(\"a xor b is {0}\", a ^ b);\n            Console.WriteLine(\"not a is {0}\", ~a);\n            Console.WriteLine(\"a lshift b is {0}\", a << b);\n            Console.WriteLine(\"a arshift b is {0}\", a >> b); \n                                                             \n            uint c = (uint)a;\n            Console.WriteLine(\"c rshift b is {0}\", c >> b); \n                                                            \n            \n        }\n"}
{"id": 45320, "name": "Dragon curve", "Python": "l = 3\nints = 13\n\ndef setup():\n  size(700, 600)\n  background(0, 0, 255)\n  translate(150, 100)\n  stroke(255)\n  turn_left(l, ints)\n  turn_right(l, ints)\n\ndef turn_right(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(90))\n        turn_right(l, ints - 1)\n  \ndef turn_left(l, ints):\n    if ints == 0:\n        line(0, 0, 0, -l)\n        translate(0, -l)\n    else:\n        turn_left(l, ints - 1)\n        rotate(radians(-90))\n        turn_right(l, ints - 1)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.Pow(2, iter / 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n"}
{"id": 45321, "name": "Doubly-linked list_Element insertion", "Python": "def insert(anchor, new):\n    new.next = anchor.next\n    new.prev = anchor\n    anchor.next.prev = new\n    anchor.next = new\n", "C#": "static void InsertAfter(Link prev, int i)\n{\n    if (prev.next != null)\n    {\n        prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };\n        prev.next = prev.next.prev;\n    }\n    else\n        prev.next = new Link() { item = i, prev = prev };\n}\n"}
{"id": 45322, "name": "Quickselect algorithm", "Python": "import random\n\ndef partition(vector, left, right, pivotIndex):\n    pivotValue = vector[pivotIndex]\n    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  \n    storeIndex = left\n    for i in range(left, right):\n        if vector[i] < pivotValue:\n            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]\n            storeIndex += 1\n    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  \n    return storeIndex\n\ndef _select(vector, left, right, k):\n    \"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.\"\n    while True:\n        pivotIndex = random.randint(left, right)     \n        pivotNewIndex = partition(vector, left, right, pivotIndex)\n        pivotDist = pivotNewIndex - left\n        if pivotDist == k:\n            return vector[pivotNewIndex]\n        elif k < pivotDist:\n            right = pivotNewIndex - 1\n        else:\n            k -= pivotDist + 1\n            left = pivotNewIndex + 1\n\ndef select(vector, k, left=None, right=None):\n    \n    if left is None:\n        left = 0\n    lv1 = len(vector) - 1\n    if right is None:\n        right = lv1\n    assert vector and k >= 0, \"Either null vector or k < 0 \"\n    assert 0 <= left <= lv1, \"left is out of range\"\n    assert left <= right <= lv1, \"right is out of range\"\n    return _select(vector, left, right, k)\n\nif __name__ == '__main__':\n    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n    print([select(v, i) for i in range(10)])\n", "C#": "\n\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickSelect\n{\n    internal static class Program\n    {\n        #region Static Members\n\n        private static void Main()\n        {\n            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n            \n            Console.WriteLine( \"Loop quick select 10 times.\" );\n            for( var i = 0 ; i < 10 ; i++ )\n            {\n                Console.Write( inputArray.NthSmallestElement( i ) );\n                if( i < 9 )\n                    Console.Write( \", \" );\n            }\n            Console.WriteLine();\n\n            \n            \n            Console.WriteLine( \"Just sort 10 elements.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            \n            Console.WriteLine( \"Get 4 smallest and sort them.\" );\n            Console.WriteLine( string.Join( \", \", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );\n            Console.WriteLine( \"< Press any key >\" );\n            Console.ReadKey();\n        }\n\n        #endregion\n    }\n\n    internal static class ArrayExtension\n    {\n        #region Static Members\n\n        \n        \n        \n        \n        \n        \n        \n        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>\n        {\n            if( count < 0 )\n                throw new ArgumentOutOfRangeException( \"count\", \"Count is smaller than 0.\" );\n            if( count == 0 )\n                return new T[0];\n            if( array.Length <= count )\n                return array;\n\n            return QuickSelectSmallest( array, count - 1 ).Take( count );\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>\n        {\n            if( n < 0 || n > array.Length - 1 )\n                throw new ArgumentOutOfRangeException( \"n\", n, string.Format( \"n should be between 0 and {0} it was {1}.\", array.Length - 1, n ) );\n            if( array.Length == 0 )\n                throw new ArgumentException( \"Array is empty.\", \"array\" );\n            if( array.Length == 1 )\n                return array[ 0 ];\n\n            return QuickSelectSmallest( array, n )[ n ];\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>\n        {\n            \n            \n            var partiallySortedArray = (T[]) input.Clone();\n           \n            \n            var startIndex = 0;\n            var endIndex = input.Length - 1;\n            \n            \n            \n            var pivotIndex = n;\n\n            \n            var r = new Random();\n            while( endIndex > startIndex )\n            {\n                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );\n                if( pivotIndex == n )\n                    \n                    break;\n                if( pivotIndex > n )\n                    \n                    endIndex = pivotIndex - 1;\n                else                    \n                    \n                    startIndex = pivotIndex + 1;\n\n                \n                \n                pivotIndex = r.Next( startIndex,  endIndex );\n            }\n            return partiallySortedArray;\n        }\n\n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        \n        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>\n        {\n            var pivotValue = array[ pivotIndex ];\n            \n            array.Swap( pivotIndex, endIndex );\n            for( var i = startIndex ; i < endIndex ; i++ )\n            {\n                if( array[ i ].CompareTo( pivotValue ) > 0 )\n                    continue;\n\n                \n                array.Swap( i, startIndex );\n                \n                startIndex++;\n            }\n            \n            array.Swap( endIndex, startIndex );\n            return startIndex;\n        }\n\n        private static void Swap<T>( this T[] array, int index1, int index2 )\n        {\n            if( index1 == index2 )\n                return;\n\n            var temp = array[ index1 ];\n            array[ index1 ] = array[ index2 ];\n            array[ index2 ] = temp;\n        }\n\n        #endregion\n    }\n}\n"}
{"id": 45323, "name": "Non-decimal radices_Convert", "Python": "i = int('1a',16)  \n", "C#": "public static class BaseConverter {\n\n    \n    \n    \n    \n    \n    \n    public static long stringToLong(string s, int b) {\n\n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        checked {\n\n            int slen = s.Length;\n            long result = 0;\n            bool isNegative = false;\n\n            for ( int i = 0; i < slen; i++ ) {\n\n                char c = s[i];\n                int num;\n\n                if ( c == '-' ) {\n                    \n                    if ( i != 0 )\n                        throw new ArgumentException(\"A negative sign is allowed only as the first character of the string.\", \"s\");\n\n                    isNegative = true;\n                    continue;\n                }\n\n                if ( c > 0x2F && c < 0x3A )\n                    \n                    num = c - 0x30;\n                else if ( c > 0x40 && c < 0x5B )\n                    \n                    \n                    num = c - 0x37;  \n                else if ( c > 0x60 && c < 0x7B )\n                    \n                    \n                    num = c - 0x57;  \n                else\n                    throw new ArgumentException(\"The string contains an invalid character '\" + c + \"'\", \"s\");\n\n                \n\n                if ( num >= b )\n                    throw new ArgumentException(\"The string contains a character '\" + c + \"' which is not allowed in base \" + b, \"s\");\n\n                \n\n                result *= b;\n                result += num;\n\n            }\n\n            if ( isNegative )\n                result = -result;\n\n            return result;\n\n        }\n\n    }\n\n    \n    \n    \n    \n    \n    \n    public static string longToString(long n, int b) {\n        \n        \n        \n        \n        if ( b < 2 || b > 36 )\n            throw new ArgumentException(\"Base must be between 2 and 36\", \"b\");\n\n        \n\n        if ( b == 10 )\n            return n.ToString();\n\n        checked {\n            long longBase = b;\n            \n            StringBuilder sb = new StringBuilder();\n            \n            if ( n < 0 ) {\n                \n                n = -n;\n                sb.Append('-');\n            }\n            \n            long div = 1;\n            while ( n / div >= b )\n                \n                \n                div *= b;\n            \n            while ( true ) {\n                byte digit = (byte) (n / div);\n            \n                if ( digit < 10 )\n                    \n                    sb.Append((char) (digit + 0x30));\n                else\n                    \n                    sb.Append((char) (digit + 0x57));  \n            \n                if ( div == 1 )\n                    \n                    break;\n            \n                n %= div;\n                div /= b;\n            }\n            \n            return sb.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 45324, "name": "Walk a directory_Recursively", "Python": "from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n    print(path)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace RosettaRecursiveDirectory\n{\n    class Program\n    {\n        static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)\n        {\n            var directoryStack = new Stack<DirectoryInfo>();\n            directoryStack.Push(new DirectoryInfo(rootPath));\n            while (directoryStack.Count > 0)\n            {\n                var dir = directoryStack.Pop();\n                try\n                {\n                    foreach (var i in dir.GetDirectories())\n                        directoryStack.Push(i);\n                }\n                catch (UnauthorizedAccessException) {\n                    continue; \n                }\n                foreach (var f in dir.GetFiles().Where(Pattern)) \n                    yield return f;\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n            foreach (var file in TraverseDirectory(@\"C:\\Windows\", f => f.Extension == \".wmv\"))\n                Console.WriteLine(file.FullName);\n            Console.WriteLine(\"Done.\");\n        }\n    }\n}\n"}
{"id": 45325, "name": "CRC-32", "Python": ">>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import zlib\n>>> hex(zlib.crc32(s))\n'0x414fa339'\n\n>>> import binascii\n>>> hex(binascii.crc32(s))\n'0x414fa339'\n", "C#": "    \n    \n    \n    public class Crc32\n    {\n        #region Constants\n        \n        \n        \n        private const UInt32 s_generator = 0xEDB88320;\n        #endregion\n\n        #region Constructors\n        \n        \n        \n        public Crc32()\n        {\n            \n            m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n            {\n                var tableEntry = (uint)i;\n                for (var j = 0; j < 8; ++j)\n                {\n                    tableEntry = ((tableEntry & 1) != 0)\n                        ? (s_generator ^ (tableEntry >> 1)) \n                        : (tableEntry >> 1);\n                }\n                return tableEntry;\n            }).ToArray();\n        }\n        #endregion\n\n        #region Methods\n        \n        \n        \n        \n        \n        public UInt32 Get<T>(IEnumerable<T> byteStream)\n        {\n            try\n            {\n                \n                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n                          (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n            }\n            catch (FormatException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (InvalidCastException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n            catch (OverflowException e)\n            {\n                throw new CrcException(\"Could not read the stream out as bytes.\", e);\n            }\n        }\n        #endregion\n\n        #region Fields\n        \n        \n        \n        private readonly UInt32[] m_checksumTable;\n\n        #endregion\n    }\n"}
{"id": 45326, "name": "Classes", "Python": "class MyClass:\n    name2 = 2 \n\n    def __init__(self):\n        \n        self.name1 = 0 \n  \n    def someMethod(self):\n        \n        self.name1 = 1\n        MyClass.name2 = 3\n  \n  \nmyclass = MyClass() \n\nclass MyOtherClass:\n    count = 0  \n    def __init__(self, name, gender=\"Male\", age=None):\n        \n        MyOtherClass.count += 1\n        self.name = name\n        self.gender = gender\n        if age is not None:\n            self.age = age\n    def __del__(self):\n        MyOtherClass.count -= 1\n\nperson1 = MyOtherClass(\"John\")\nprint person1.name, person1.gender  \nprint person1.age                   \nperson2 = MyOtherClass(\"Jane\", \"Female\", 23)\nprint person2.name, person2.gender, person2.age  \n", "C#": "public class MyClass\n{\n    public MyClass()\n    {\n    }\n    public void SomeMethod()\n    {\n    }\n    private int _variable;\n    public int Variable\n    {\n        get { return _variable; }\n        set { _variable = value; }\n    }\n    public static void Main()\n    {\n        \n        MyClass instance = new MyClass();\n        \n        instance.SomeMethod();\n        \n        instance.Variable = 99;\n        \n        System.Console.WriteLine( \"Variable=\" + instance.Variable.ToString() );\n    }\n}\n"}
{"id": 45327, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 45328, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 45329, "name": "Kaprekar numbers", "Python": ">>> def k(n):\n\tn2 = str(n**2)\n\tfor i in range(len(n2)):\n\t\ta, b = int(n2[:i] or 0), int(n2[i:])\n\t\tif b and a + b == n:\n\t\t\treturn n\n\t\t\t\n\n\t\t\n>>> [x for x in range(1,10000) if k(x)]\n[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]\n>>> len([x for x in range(1,1000000) if k(x)])\n54\n>>>\n", "C#": "using System;\nusing System.Collections.Generic;\n\npublic class KaprekarNumbers {\n\n    \n    \n    \n    public static void Main() {\n        int count = 0;\n\n        foreach ( ulong i in _kaprekarGenerator(999999) ) {\n            Console.WriteLine(i);\n            count++;\n        }\n\n        Console.WriteLine(\"There are {0} Kaprekar numbers less than 1000000.\", count);\n    }\n\n    \n    \n    \n    \n    \n    private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {\n\n        ulong next = 1;\n\n        \n        yield return next;\n\n        for ( next = 2; next <= max; next++ ) {\n\n            ulong square = next * next;\n\n            for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {\n                \n                \n\n                \n                if ( square <= check )\n                    break;\n\n                \n                \n                \n                \n                \n\n                ulong r = square % check;\n                ulong q = (square - r) / check;\n\n                if ( r != 0 && q + r == next ) {\n                    yield return next;\n                    break;\n                }\n            }\n\n        }\n\n    }\n\n}\n"}
{"id": 45330, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 45331, "name": "Hofstadter Figure-Figure sequences", "Python": "def ffr(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffr.r[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        ffr_n_1 = ffr(n-1)\n        lastr = r[-1]\n        \n        s += list(range(s[-1] + 1, lastr))\n        if s[-1] < lastr: s += [lastr + 1]\n        \n        len_s = len(s)\n        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n        ans = ffr_n_1 + ffs_n_1\n        r.append(ans)\n        return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n    if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n    try:\n        return ffs.s[n]\n    except IndexError:\n        r, s = ffr.r, ffs.s\n        for i in range(len(r), n+2):\n            ffr(i)\n            if len(s) > n:\n                return s[n]\n        raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n    first10 = [ffr(i) for i in range(1,11)]\n    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n    print(\"ffr(n) for n = [1..10] is\", first10)\n    \n    bin = [None] + [0]*1000\n    for i in range(40, 0, -1):\n        bin[ffr(i)] += 1\n    for i in range(960, 0, -1):\n        bin[ffs(i)] += 1\n    if all(b == 1 for b in bin[1:1000]):\n        print(\"All Integers 1..1000 found OK\")\n    else:\n        print(\"All Integers 1..1000 NOT found only once: ERROR\")\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HofstadterFigureFigure\n{\n\tclass HofstadterFigureFigure\n\t{\n\t\treadonly List<int> _r = new List<int>() {1};\n\t\treadonly List<int> _s = new List<int>();\n\n\t\tpublic IEnumerable<int> R()\n\t\t{\n\t\t\tint iR = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iR >= _r.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _r[iR++];\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable<int> S()\n\t\t{\n\t\t\tint iS = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (iS >= _s.Count)\n\t\t\t\t{\n\t\t\t\t\tAdvance();\n\t\t\t\t}\n\t\t\t\tyield return _s[iS++];\n\t\t\t}\n\t\t}\n\n\t\tprivate void Advance()\n\t\t{\n\t\t\tint rCount = _r.Count;\n\t\t\tint oldR = _r[rCount - 1];\n\t\t\tint sVal;\n\t\t\t\n\t\t\t\n\t\t\tswitch (rCount)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\tsVal = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsVal = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsVal = _s[rCount - 1];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_r.Add(_r[rCount - 1] + sVal);\n\t\t\tint newR = _r[rCount];\n\t\t\tfor (int iS = oldR + 1; iS < newR; iS++)\n\t\t\t{\n\t\t\t\t_s.Add(iS);\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Program\n\t{\n\t\tstatic void Main()\n\t\t{\n\t\t\tvar hff = new HofstadterFigureFigure();\n\t\t\tvar rs = hff.R();\n\t\t\tvar arr = rs.Take(40).ToList();\n\n\t\t\tforeach(var v in arr.Take(10))\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"{0}\", v);\n\t\t\t}\n\n\t\t\tvar hs = new HashSet<int>(arr);\n\t\t\ths.UnionWith(hff.S().Take(960));\n\t\t\tConsole.WriteLine(hs.Count == 1000 ? \"Verified\" : \"Oops!  Something's wrong!\");\n\t\t}\n\t}\n}\n"}
{"id": 45332, "name": "Anonymous recursion", "Python": ">>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\n>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))\n>>> [ Y(fib)(i) for i in range(-2, 10) ]\n[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n", "C#": "static int Fib(int n)\n{\n    if (n < 0) throw new ArgumentException(\"Must be non negativ\", \"n\");\n \n    Func<int, int> fib = null; \n    fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;\n    return fib(n);\n}\n"}
{"id": 45333, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 45334, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 45335, "name": "Universal Turing machine", "Python": "from __future__ import print_function\n\ndef run_utm(\n        state = None,\n        blank = None,\n        rules = [],\n        tape = [],\n        halt = None,\n        pos = 0):\n    st = state\n    if not tape: tape = [blank]\n    if pos < 0: pos += len(tape)\n    if pos >= len(tape) or pos < 0: raise Error( \"bad init position\")\n    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)\n\n    while True:\n        print(st, '\\t', end=\" \")\n        for i, v in enumerate(tape):\n            if i == pos: print(\"[%s]\" % (v,), end=\" \")\n            else: print(v, end=\" \")\n        print()\n\n        if st == halt: break\n        if (st, tape[pos]) not in rules: break\n\n        (v1, dr, s1) = rules[(st, tape[pos])]\n        tape[pos] = v1\n        if dr == 'left':\n            if pos > 0: pos -= 1\n            else: tape.insert(0, blank)\n        if dr == 'right':\n            pos += 1\n            if pos >= len(tape): tape.append(blank) \n        st = s1\n    \n\n\n            \nprint(\"incr machine\\n\")\nrun_utm(\n    halt = 'qf',\n\tstate = 'q0',\n\ttape = list(\"111\"),\n\tblank = 'B',\n\trules = map(tuple, \n               [\"q0 1 1 right q0\".split(),\n\t\t        \"q0 B 1 stay  qf\".split()]\n        )\n    )\n\nprint(\"\\nbusy beaver\\n\")\nrun_utm(\n    halt = 'halt',\n\tstate = 'a',\n\tblank = '0',\n\trules = map(tuple,\n        [\"a 0 1 right b\".split(),\n         \"a 1 1 left  c\".split(),\n         \"b 0 1 left  a\".split(),\n         \"b 1 1 right b\".split(),\n         \"c 0 1 left  b\".split(),\n         \"c 1 1 stay  halt\".split()]\n        )\n    )\n\nprint(\"\\nsorting test\\n\")\nrun_utm(halt = 'STOP',\n\tstate = 'A',\n\tblank = '0',\n\ttape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split(),\n\trules = map(tuple,\n       [\"A 1 1 right A\".split(),\n\t\t\"A 2 3 right B\".split(),\n\t\t\"A 0 0 left  E\".split(),\n\t\t\"B 1 1 right B\".split(),\n\t\t\"B 2 2 right B\".split(),\n\t\t\"B 0 0 left  C\".split(),\n\t\t\"C 1 2 left  D\".split(),\n\t\t\"C 2 2 left  C\".split(),\n\t\t\"C 3 2 left  E\".split(),\n\t\t\"D 1 1 left  D\".split(),\n\t\t\"D 2 2 left  D\".split(),\n\t\t\"D 3 1 right A\".split(),\n\t\t\"E 1 1 left  E\".split(),\n\t\t\"E 0 0 right STOP\".split()]\n        )\n    )\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class TuringMachine\n{\n    public static async Task Main() {\n        var fiveStateBusyBeaver = new TuringMachine(\"A\", '0', \"H\").WithTransitions(\n            (\"A\", '0', '1', Right, \"B\"),\n            (\"A\", '1', '1', Left,  \"C\"),\n            (\"B\", '0', '1', Right, \"C\"),\n            (\"B\", '1', '1', Right, \"B\"),\n            (\"C\", '0', '1', Right, \"D\"),\n            (\"C\", '1', '0', Left,  \"E\"),\n            (\"D\", '0', '1', Left,  \"A\"),\n            (\"D\", '1', '1', Left,  \"D\"),\n            (\"E\", '0', '1', Stay,  \"H\"),\n            (\"E\", '1', '0', Left,  \"A\")\n        );\n        var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();\n\n        var incrementer = new TuringMachine(\"q0\", 'B', \"qf\").WithTransitions(\n            (\"q0\", '1', '1', Right, \"q0\"),\n            (\"q0\", 'B', '1', Stay,  \"qf\")\n        )\n        .WithInput(\"111\");\n        foreach (var _ in incrementer.Run()) PrintLine(incrementer);\n        PrintResults(incrementer);\n\n        var threeStateBusyBeaver = new TuringMachine(\"a\", '0', \"halt\").WithTransitions(\n            (\"a\", '0', '1', Right, \"b\"),\n            (\"a\", '1', '1', Left,  \"c\"),\n            (\"b\", '0', '1', Left,  \"a\"),\n            (\"b\", '1', '1', Right, \"b\"),\n            (\"c\", '0', '1', Left,  \"b\"),\n            (\"c\", '1', '1', Stay,  \"halt\")\n        );\n        foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);\n        PrintResults(threeStateBusyBeaver);\n\n        var sorter = new TuringMachine(\"A\", '*', \"X\").WithTransitions(\n            (\"A\", 'a', 'a', Right, \"A\"),\n            (\"A\", 'b', 'B', Right, \"B\"),\n            (\"A\", '*', '*', Left,  \"E\"),\n            (\"B\", 'a', 'a', Right, \"B\"),\n            (\"B\", 'b', 'b', Right, \"B\"),\n            (\"B\", '*', '*', Left,  \"C\"),\n            (\"C\", 'a', 'b', Left,  \"D\"),\n            (\"C\", 'b', 'b', Left,  \"C\"),\n            (\"C\", 'B', 'b', Left,  \"E\"),\n            (\"D\", 'a', 'a', Left,  \"D\"),\n            (\"D\", 'b', 'b', Left,  \"D\"),\n            (\"D\", 'B', 'a', Right, \"A\"),\n            (\"E\", 'a', 'a', Left,  \"E\"),\n            (\"E\", '*', '*', Right, \"X\")\n        )\n        .WithInput(\"babbababaa\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        sorter.Reset().WithInput(\"bbbababaaabba\");\n        sorter.Run().Last();\n        Console.WriteLine(\"Sorted: \" + sorter.TapeString);\n        PrintResults(sorter);\n\n        Console.WriteLine(await busyBeaverTask);\n        PrintResults(fiveStateBusyBeaver);\n\n        void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + \"\\tState \" + tm.State);\n\n        void PrintResults(TuringMachine tm) {\n            Console.WriteLine($\"End state: {tm.State} = {(tm.Success ? \"Success\" : \"Failure\")}\");\n            Console.WriteLine(tm.Steps + \" steps\");\n            Console.WriteLine(\"tape length: \" + tm.TapeLength);\n            Console.WriteLine();\n        }\n    }\n\n    public const int Left = -1, Stay = 0, Right = 1;\n    private readonly Tape tape;\n    private readonly string initialState;\n    private readonly HashSet<string> terminatingStates;\n    private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;\n\n    public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {\n        State = this.initialState = initialState;\n        tape = new Tape(blankSymbol);\n        this.terminatingStates = terminatingStates.ToHashSet();\n    }\n\n    public TuringMachine WithTransitions(\n        params (string state, char read, char write, int move, string toState)[] transitions)\n    {\n        this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));\n        return this;\n    }\n\n    public TuringMachine Reset() {\n        State = initialState;\n        Steps = 0;\n        tape.Reset();\n        return this;\n    }\n\n    public TuringMachine WithInput(string input) {\n        tape.Input(input);\n        return this;\n    }\n\n    public int Steps { get; private set; }\n    public string State { get; private set; }\n    public bool Success => terminatingStates.Contains(State);\n    public int TapeLength => tape.Length;\n    public string TapeString => tape.ToString();\n\n    public IEnumerable<string> Run() {\n        yield return State;\n        while (Step()) yield return State;\n    }\n\n    public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {\n        var chrono = Stopwatch.StartNew();\n        await RunAsync(cancel);\n        chrono.Stop();\n        return chrono.Elapsed;\n    }\n\n    public Task RunAsync(CancellationToken cancel = default)\n        => Task.Run(() => {\n            while (Step()) cancel.ThrowIfCancellationRequested();\n        });\n\n    private bool Step() {\n        if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;\n        tape.Current = action.write;\n        tape.Move(action.move);\n        State = action.toState;\n        Steps++;\n        return true;\n    }\n\n\n    private class Tape\n    {\n        private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();\n        private int head = 0;\n        private char blank;\n\n        public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);\n\n        public void Reset() {\n            backwardTape.Clear();\n            forwardTape.Clear();\n            head = 0;\n            forwardTape.Add(blank);\n        }\n\n        public void Input(string input) {\n            Reset();\n            forwardTape.Clear();\n            forwardTape.AddRange(input);\n        }\n\n        public void Move(int direction) {\n            head += direction;\n            if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);\n            if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);\n        }\n\n        public char Current {\n            get => head < 0 ? backwardTape[~head] : forwardTape[head];\n            set {\n                if (head < 0) backwardTape[~head] = value;\n                else forwardTape[head] = value;\n            }\n        }\n\n        public int Length => backwardTape.Count + forwardTape.Count;\n\n        public override string ToString() {\n            int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;\n            var builder = new StringBuilder(\" \", Length * 2 + 1);\n            if (backwardTape.Count > 0) {\n                builder.Append(string.Join(\" \", backwardTape)).Append(\" \");\n                if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');\n                for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);\n            }\n            builder.Append(string.Join(\" \", forwardTape)).Append(\" \");\n            if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');\n            return builder.ToString();\n        }\n\n    }\n\n}\n"}
{"id": 45336, "name": "Create a file", "Python": "import os\nfor directory in ['/', './']:\n  open(directory + 'output.txt', 'w').close()  \n  os.mkdir(directory + 'docs')                 \n", "C#": "using System;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        File.Create(\"output.txt\");\n        File.Create(@\"\\output.txt\");\n\n        Directory.CreateDirectory(\"docs\");\n        Directory.CreateDirectory(@\"\\docs\");\n    }\n}\n"}
{"id": 45337, "name": "Delegates", "Python": "class Delegator:\n   def __init__(self):\n      self.delegate = None\n   def operation(self):\n       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n          return self.delegate.thing()\n       return 'default implementation'\n\nclass Delegate:\n   def thing(self):\n      return 'delegate implementation'\n\nif __name__ == '__main__':\n\n   \n   a = Delegator()\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = 'A delegate may be any object'\n   assert a.operation() == 'default implementation'\n\n   \n   a.delegate = Delegate()\n   assert a.operation() == 'delegate implementation'\n", "C#": "using System;\n\ninterface IOperable\n{\n    string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n    public string Operate()\n    {\n        return \"Delegate implementation.\";\n    }\n}\n\nclass Delegator : IOperable\n{\n    object Delegate;\n\n    public string Operate()\n    {\n        var operable = Delegate as IOperable;\n        return operable != null ? operable.Operate() : \"Default implementation.\";\n    }\n\n    static void Main()\n    {\n        var delegator = new Delegator();\n        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n        {\n            delegator.Delegate = @delegate;\n            Console.WriteLine(delegator.Operate());\n        }\n    }\n}\n"}
{"id": 45338, "name": "Enforced immutability", "Python": ">>> s = \"Hello\"\n>>> s[0] = \"h\"\n\nTraceback (most recent call last):\n  File \"<pyshell\n    s[0] = \"h\"\nTypeError: 'str' object does not support item assignment\n", "C#": "readonly DateTime now = DateTime.Now;\n"}
{"id": 45339, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 45340, "name": "Bacon cipher", "Python": "import string\n\nsometext = .lower()\n\nlc2bin = {ch: '{:05b}'.format(i) \n          for i, ch in enumerate(string.ascii_lowercase + ' .')}\nbin2lc = {val: key for key, val in lc2bin.items()}\n\nphrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()\n\ndef to_5binary(msg):\n    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))\n\ndef encrypt(message, text):\n    bin5 = to_5binary(message)\n    textlist = list(text.lower())\n    out = []\n    for capitalise in bin5:\n        while textlist:\n            ch = textlist.pop(0)\n            if ch.isalpha():\n                if capitalise:\n                    ch = ch.upper()\n                out.append(ch)\n                break\n            else:\n                out.append(ch)\n        else:\n            raise Exception('ERROR: Ran out of characters in sometext')\n    return ''.join(out) + '...'\n\n\ndef  decrypt(bacontext):\n    binary = []\n    bin5 = []\n    out = []\n    for ch in bacontext:\n        if ch.isalpha():\n            binary.append('1' if ch.isupper() else '0')\n            if len(binary) == 5:\n                bin5 = ''.join(binary)\n                out.append(bin2lc[bin5])\n                binary = []\n    return ''.join(out)\n                \n\nprint('PLAINTEXT = \\n%s\\n' % phrase)\nencrypted = encrypt(phrase, sometext)\nprint('ENCRYPTED = \\n%s\\n' % encrypted)\ndecrypted = decrypt(encrypted)\nprint('DECRYPTED = \\n%s\\n' % decrypted)\nassert phrase == decrypted, 'Round-tripping error'\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BaconCipher {\n    class Program {\n        private static Dictionary<char, string> codes = new Dictionary<char, string> {\n            {'a', \"AAAAA\" }, {'b', \"AAAAB\" }, {'c', \"AAABA\" }, {'d', \"AAABB\" }, {'e', \"AABAA\" },\n            {'f', \"AABAB\" }, {'g', \"AABBA\" }, {'h', \"AABBB\" }, {'i', \"ABAAA\" }, {'j', \"ABAAB\" },\n            {'k', \"ABABA\" }, {'l', \"ABABB\" }, {'m', \"ABBAA\" }, {'n', \"ABBAB\" }, {'o', \"ABBBA\" },\n            {'p', \"ABBBB\" }, {'q', \"BAAAA\" }, {'r', \"BAAAB\" }, {'s', \"BAABA\" }, {'t', \"BAABB\" },\n            {'u', \"BABAA\" }, {'v', \"BABAB\" }, {'w', \"BABBA\" }, {'x', \"BABBB\" }, {'y', \"BBAAA\" },\n            {'z', \"BBAAB\" }, {' ', \"BBBAA\" }, \n        };\n\n        private static string Encode(string plainText, string message) {\n            string pt = plainText.ToLower();\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in pt) {\n                if ('a' <= c && c <= 'z') sb.Append(codes[c]);\n                else sb.Append(codes[' ']);\n            }\n            string et = sb.ToString();\n            string mg = message.ToLower();  \n            sb.Length = 0;\n            int count = 0;\n            foreach (char c in mg) {\n                if ('a' <= c && c <= 'z') {\n                    if (et[count] == 'A') sb.Append(c);\n                    else sb.Append((char)(c - 32)); \n                    count++;\n                    if (count == et.Length) break;\n                }\n                else sb.Append(c);\n            }\n\n            return sb.ToString();\n        }\n\n        private static string Decode(string message) {\n            StringBuilder sb = new StringBuilder();\n            foreach (char c in message) {\n                if ('a' <= c && c <= 'z') sb.Append('A');\n                else if ('A' <= c && c <= 'Z') sb.Append('B');\n            }\n            string et = sb.ToString();\n            sb.Length = 0;\n            for (int i = 0; i < et.Length; i += 5) {\n                string quintet = et.Substring(i, 5);\n                char key = codes.Where(a => a.Value == quintet).First().Key;\n                sb.Append(key);\n            }\n            return sb.ToString();\n        }\n\n        static void Main(string[] args) {\n            string plainText = \"the quick brown fox jumps over the lazy dog\";\n            string message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n                \"this task is to implement a program for encryption and decryption of \" +\n                \"plaintext using the simple alphabet of the baconian cipher or some \" +\n                \"other kind of representation of this alphabet (make anything signify anything). \" +\n                \"the baconian alphabet may optionally be extended to encode all lower \" +\n                \"case characters individually and/or adding a few punctuation characters \" +\n                \"such as the space.\";\n            string cipherText = Encode(plainText, message);\n            Console.WriteLine(\"Cipher text ->\\n{0}\", cipherText);\n            string decodedText = Decode(cipherText);\n            Console.WriteLine(\"\\nHidden text ->\\n{0}\", decodedText);\n        }\n    }\n}\n"}
{"id": 45341, "name": "Spiral matrix", "Python": "def spiral(n):\n    dx,dy = 1,0            \n    x,y = 0,0              \n    myarray = [[None]* n for j in range(n)]\n    for i in xrange(n**2):\n        myarray[x][y] = i\n        nx,ny = x+dx, y+dy\n        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:\n            x,y = nx,ny\n        else:\n            dx,dy = -dy,dx\n            x,y = x+dx, y+dy\n    return myarray\n\ndef printspiral(myarray):\n    n = range(len(myarray))\n    for y in n:\n        for x in n:\n            print \"%2i\" % myarray[x][y],\n        print\n\nprintspiral(spiral(5))\n", "C#": "public int[,] Spiral(int n) {\n    int[,] result = new int[n, n];\n\n    int pos = 0;\n    int count = n;\n    int value = -n;\n    int sum = -1;\n\n    do {\n        value = -1 * value / n;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n        value *= n;\n        count--;\n        for (int i = 0; i < count; i++) {\n            sum += value;\n            result[sum / n, sum % n] = pos++;\n        }\n    } while (count > 0);\n\n    return result;\n}\n\n\n\npublic void PrintArray(int[,] array) {\n    int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;\n\n    for (int i = 0; i < array.GetLength(0); i++) {\n        for (int j = 0; j < array.GetLength(1); j++) {\n            Console.Write(array[i, j].ToString().PadLeft(n, ' '));\n        }\n        Console.WriteLine();\n    }\n}\n"}
{"id": 45342, "name": "Faulhaber's triangle", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 45343, "name": "Faulhaber's triangle", "Python": "\n\nfrom itertools import accumulate, chain, count, islice\nfrom fractions import Fraction\n\n\n\ndef faulhaberTriangle(m):\n    \n    def go(rs, n):\n        def f(x, y):\n            return Fraction(n, x) * y\n        xs = list(map(f, islice(count(2), m), rs))\n        return [Fraction(1 - sum(xs), 1)] + xs\n\n    return list(accumulate(\n        [[]] + list(islice(count(0), 1 + m)),\n        go\n    ))[1:]\n\n\n\ndef faulhaberSum(p, n):\n    \n    def go(x, y):\n        return y * (n ** x)\n\n    return sum(\n        map(go, count(1), faulhaberTriangle(p)[-1])\n    )\n\n\n\ndef main():\n    \n\n    fs = faulhaberTriangle(9)\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            compose(concat)(\n                fmap(showRatio(3)(3))\n            )\n        )(\n            index(fs)\n        )(range(0, len(fs)))\n    )\n    print('')\n    print(\n        faulhaberSum(17, 1000)\n    )\n\n\n\n\n\n\ndef fTable(s):\n    \n    def gox(xShow):\n        def gofx(fxShow):\n            def gof(f):\n                def goxs(xs):\n                    ys = [xShow(x) for x in xs]\n                    w = max(map(len, ys))\n\n                    def arrowed(x, y):\n                        return y.rjust(w, ' ') + ' -> ' + (\n                            fxShow(f(x))\n                        )\n                    return s + '\\n' + '\\n'.join(\n                        map(arrowed, xs, ys)\n                    )\n                return goxs\n            return gof\n        return gofx\n    return gox\n\n\n\n\n\ndef compose(g):\n    \n    return lambda f: lambda x: g(f(x))\n\n\n\n\ndef concat(xs):\n    \n    def f(ys):\n        zs = list(chain(*ys))\n        return ''.join(zs) if isinstance(ys[0], str) else zs\n\n    return (\n        f(xs) if isinstance(xs, list) else (\n            chain.from_iterable(xs)\n        )\n    ) if xs else []\n\n\n\ndef fmap(f):\n    \n    def go(xs):\n        return list(map(f, xs))\n\n    return go\n\n\n\ndef index(xs):\n    \n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n\ndef showRatio(m):\n    \n    def go(n):\n        def f(r):\n            d = r.denominator\n            return str(r.numerator).rjust(m, ' ') + (\n                ('/' + str(d).ljust(n, ' ')) if 1 != d else (\n                    ' ' * (1 + n)\n                )\n            )\n        return f\n    return go\n\n\n\nif __name__ == '__main__':\n    main()\n", "C#": "using System;\n\nnamespace FaulhabersTriangle {\n    internal class Frac {\n        private long num;\n        private long denom;\n\n        public static readonly Frac ZERO = new Frac(0, 1);\n        public static readonly Frac ONE = new Frac(1, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) {\n                throw new ArgumentException(\"d must not be zero\");\n            }\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            }\n            else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.Abs(Gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        private static long Gcd(long a, long b) {\n            if (b == 0) {\n                return a;\n            }\n            return Gcd(b, a % b);\n        }\n\n        public static Frac operator -(Frac self) {\n            return new Frac(-self.num, self.denom);\n        }\n\n        public static Frac operator +(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);\n        }\n\n        public static Frac operator -(Frac lhs, Frac rhs) {\n            return lhs + -rhs;\n        }\n\n        public static Frac operator *(Frac lhs, Frac rhs) {\n            return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n        }\n\n        public static bool operator <(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x < y;\n        }\n\n        public static bool operator >(Frac lhs, Frac rhs) {\n            double x = (double)lhs.num / lhs.denom;\n            double y = (double)rhs.num / rhs.denom;\n            return x > y;\n        }\n\n        public static bool operator ==(Frac lhs, Frac rhs) {\n            return lhs.num == rhs.num && lhs.denom == rhs.denom;\n        }\n\n        public static bool operator !=(Frac lhs, Frac rhs) {\n            return lhs.num != rhs.num || lhs.denom != rhs.denom;\n        }\n\n        public override string ToString() {\n            if (denom == 1) {\n                return num.ToString();\n            }\n            return string.Format(\"{0}/{1}\", num, denom);\n        }\n\n        public override bool Equals(object obj) {\n            var frac = obj as Frac;\n            return frac != null &&\n                   num == frac.num &&\n                   denom == frac.denom;\n        }\n\n        public override int GetHashCode() {\n            var hashCode = 1317992671;\n            hashCode = hashCode * -1521134295 + num.GetHashCode();\n            hashCode = hashCode * -1521134295 + denom.GetHashCode();\n            return hashCode;\n        }\n    }\n\n    class Program {\n        static Frac Bernoulli(int n) {\n            if (n < 0) {\n                throw new ArgumentException(\"n may not be negative or zero\");\n            }\n            Frac[] a = new Frac[n + 1];\n            for (int m = 0; m <= n; m++) {\n                a[m] = new Frac(1, m + 1);\n                for (int j = m; j >= 1; j--) {\n                    a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);\n                }\n            }\n            \n            if (n != 1) return a[0];\n            return -a[0];\n        }\n\n        static int Binomial(int n, int k) {\n            if (n < 0 || k < 0 || n < k) {\n                throw new ArgumentException();\n            }\n            if (n == 0 || k == 0) return 1;\n            int num = 1;\n            for (int i = k + 1; i <= n; i++) {\n                num = num * i;\n            }\n            int denom = 1;\n            for (int i = 2; i <= n - k; i++) {\n                denom = denom * i;\n            }\n            return num / denom;\n        }\n\n        static Frac[] FaulhaberTriangle(int p) {\n            Frac[] coeffs = new Frac[p + 1];\n            for (int i = 0; i < p + 1; i++) {\n                coeffs[i] = Frac.ZERO;\n            }\n            Frac q = new Frac(1, p + 1);\n            int sign = -1;\n            for (int j = 0; j <= p; j++) {\n                sign *= -1;\n                coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);\n            }\n            return coeffs;\n        }\n\n        static void Main(string[] args) {\n            for (int i = 0; i < 10; i++) {\n                Frac[] coeffs = FaulhaberTriangle(i);\n                foreach (Frac coeff in coeffs) {\n                    Console.Write(\"{0,5}  \", coeff);\n                }\n                Console.WriteLine();\n            }\n        }\n    }\n}\n"}
{"id": 45344, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 45345, "name": "Command-line arguments", "Python": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n", "C#": "using System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n"}
{"id": 45346, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 45347, "name": "Array concatenation", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "C#": "using System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n"}
{"id": 45348, "name": "User input_Text", "Python": "   string = raw_input(\"Input a string: \")\n", "C#": "using System;\n\nnamespace C_Sharp_Console {\n\n    class example {\n\n        static void Main() {\n            string word;\n            int num;\n            \n            Console.Write(\"Enter an integer: \");\n            num = Console.Read();\n            Console.Write(\"Enter a String: \");\n            word = Console.ReadLine();\n        }\n    }\n}\n"}
{"id": 45349, "name": "Knapsack problem_0-1", "Python": "from itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) \nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name : \" + Name + \"        Wieght : \" + Weight + \"       Value : \" + Value + \"     ResultWV : \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n"}
{"id": 45350, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 45351, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 45352, "name": "Cartesian product of two or more lists", "Python": "import itertools\n\ndef cp(lsts):\n    return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n    from pprint import pprint as pp\n    \n    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),\n                  ((1, 2, 3), (30,), (500, 100)),\n                  ((1, 2, 3), (), (500, 100))]:\n        print(lists, '=>')\n        pp(cp(lists), indent=2)\n", "C#": "using System;\npublic class Program\n{\n    public static void Main()\n    {\n        int[] empty = new int[0];\n        int[] list1 = { 1, 2 };\n        int[] list2 = { 3, 4 };\n        int[] list3 = { 1776, 1789 };\n        int[] list4 = { 7, 12 };\n        int[] list5 = { 4, 14, 23 };\n        int[] list6 = { 0, 1 };\n        int[] list7 = { 1, 2, 3 };\n        int[] list8 = { 30 };\n        int[] list9 = { 500, 100 };\n        \n        foreach (var sequenceList in new [] {\n            new [] { list1, list2 },\n            new [] { list2, list1 },\n            new [] { list1, empty },\n            new [] { empty, list1 },\n            new [] { list3, list4, list5, list6 },\n            new [] { list7, list8, list9 },\n            new [] { list7, empty, list9 }\n        }) {\n            var cart = sequenceList.CartesianProduct()\n                .Select(tuple => $\"({string.Join(\", \", tuple)})\");\n            Console.WriteLine($\"{{{string.Join(\", \", cart)}}}\");\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n            from acc in accumulator\n            from item in sequence\n            select acc.Concat(new [] { item }));\n    }\n}\n"}
{"id": 45353, "name": "First-class functions", "Python": ">>> \n>>> from math import sin, cos, acos, asin\n>>> \n>>> cube = lambda x: x * x * x\n>>> croot = lambda x: x ** (1/3.0)\n>>> \n>>> \n>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )\n>>> \n>>> funclist = [sin, cos, cube]\n>>> funclisti = [asin, acos, croot]\n>>> \n>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]\n[0.5, 0.4999999999999999, 0.5]\n>>>\n", "C#": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));\n        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));\n\n        var functionTuples = new[]\n        {\n            (forward: Math.Sin, backward: Math.Asin),\n            (forward: Math.Cos, backward: Math.Acos),\n            (forward: cube,     backward: croot)\n        };\n\n        foreach (var ft in functionTuples)\n        {\n            Console.WriteLine(ft.backward(ft.forward(0.5)));\n        }\n    }\n}\n"}
{"id": 45354, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 45355, "name": "Proper divisors", "Python": ">>> def proper_divs2(n):\n...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}\n... \n>>> [proper_divs2(n) for n in range(1, 11)]\n[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]\n>>> \n>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])\n>>> n\n15120\n>>> length\n79\n>>>\n", "C#": "namespace RosettaCode.ProperDivisors\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal static class Program\n    {\n        private static IEnumerable<int> ProperDivisors(int number)\n        {\n            return\n                Enumerable.Range(1, number / 2)\n                    .Where(divisor => number % divisor == 0);\n        }\n\n        private static void Main()\n        {\n            foreach (var number in Enumerable.Range(1, 10))\n            {\n                Console.WriteLine(\"{0}: {{{1}}}\", number,\n                    string.Join(\", \", ProperDivisors(number)));\n            }\n\n            var record = Enumerable.Range(1, 20000).Select(number => new\n            {\n                Number = number,\n                Count = ProperDivisors(number).Count()\n            }).OrderByDescending(currentRecord => currentRecord.Count).First();\n            Console.WriteLine(\"{0}: {1}\", record.Number, record.Count);\n        }\n    }\n}\n"}
{"id": 45356, "name": "XML_Output", "Python": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t    'Burns: \"When chapman billies leave the street ...\"',\n\t\t    'Short & shrift' ] ).replace('><','>\\n<')\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static string CreateXML(Dictionary<string, string> characterRemarks)\n    {\n        var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n        var xml = new XElement(\"CharacterRemarks\", remarks);\n        return xml.ToString();\n    }\n\n    static void Main(string[] args)\n    {\n        var characterRemarks = new Dictionary<string, string>\n        {\n            { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n            { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n            { \"Emily\", \"Short & shrift\" }\n        };\n\n        string xml = CreateXML(characterRemarks);\n        Console.WriteLine(xml);\n    }\n}\n"}
{"id": 45357, "name": "Regular expressions", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "C#": "using System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n"}
{"id": 45358, "name": "Guess the number_With feedback (player)", "Python": "inclusive_range = mn, mx = (1, 10)\n\nprint( % inclusive_range)\n\ni = 0\nwhile True:\n    i += 1\n    guess = (mn+mx)//2\n    txt = input(\"Guess %2i is: %2i. The score for which is (h,l,=): \"\n                % (i, guess)).strip().lower()[0]\n    if txt not in 'hl=':\n        print(\"  I don't understand your input of '%s' ?\" % txt)\n        continue\n    if txt == 'h':\n        mx = guess-1\n    if txt == 'l':\n        mn = guess+1\n    if txt == '=':\n        print(\"  Ye-Haw!!\")\n        break\n    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):\n        print(\"Please check your scoring as I cannot find the value\")\n        break\n        \nprint(\"\\nThanks for keeping score.\")\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading; \n\nnamespace ConsoleApplication1\n{\n    class RealisticGuess \n    {\n        private int max;\n        private int min;\n        private int guess;\n\n        public void Start()\n        {\n            Console.Clear();\n            string input;\n\n            try\n            {\n                Console.WriteLine(\"Please enter the lower boundary\");\n                input = Console.ReadLine();\n                min = Convert.ToInt32(input);\n                Console.WriteLine(\"Please enter the upper boundary\");\n                input = Console.ReadLine();\n                max = Convert.ToInt32(input);\n            }\n            catch (FormatException)\n            {\n                Console.WriteLine(\"The entry you have made is invalid. Please make sure your entry is an integer and try again.\");\n                Console.ReadKey(true);\n                Start();\n            }\n            Console.WriteLine(\"Think of a number between {0} and {1}.\", min, max);\n            Thread.Sleep(2500);\n            Console.WriteLine(\"Ready?\");\n            Console.WriteLine(\"Press any key to begin.\");\n            Console.ReadKey(true);\n            Guess(min, max);\n        }\n        public void Guess(int min, int max)\n        {\n            int counter = 1;\n            string userAnswer;\n            bool correct = false;\n            Random rand = new Random();\n\n            while (correct == false)\n            {\n                guess = rand.Next(min, max);\n                Console.Clear();\n                Console.WriteLine(\"{0}\", guess);\n                Console.WriteLine(\"Is this number correct? {Y/N}\");\n                userAnswer = Console.ReadLine();\n                if (userAnswer != \"y\" && userAnswer != \"Y\" && userAnswer != \"n\" && userAnswer != \"N\")\n                {\n                    Console.WriteLine(\"Your entry is invalid. Please enter either 'Y' or 'N'\");\n                    Console.WriteLine(\"Is the number correct? {Y/N}\");\n                    userAnswer = Console.ReadLine();\n                }\n                if (userAnswer == \"y\" || userAnswer == \"Y\")\n                {\n                    correct = true;\n                }\n                if (userAnswer == \"n\" || userAnswer == \"N\")\n                {\n                    counter++;\n                    if (max == min)\n                    {\n                        Console.WriteLine(\"Error: Range Intersect. Press enter to restart the game.\");  \n                        Console.ReadKey(true);                                                          \n                        Guess(1, 101);                                                                  \n                    }\n                    Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                    userAnswer = Console.ReadLine();\n                    if (userAnswer != \"l\" && userAnswer != \"L\" && userAnswer != \"h\" && userAnswer != \"H\")\n                    {\n                        Console.WriteLine(\"Your entry is invalid. Please enter either 'L' or 'H'\");\n                        Console.WriteLine(\"Is the number you're thinking of lower or higher? {L/H}\");\n                        userAnswer = Console.ReadLine();\n                    }\n                    if (userAnswer == \"l\" || userAnswer == \"L\")\n                    {\n                        max = guess;\n                    }\n                    if (userAnswer == \"h\" || userAnswer == \"H\")\n                    {\n                        min = guess;\n                    }\n                }\n            }\n            if (correct == true)\n            {\n                EndAndLoop(counter);\n            }\n        }\n\n        public void EndAndLoop(int iterations)\n        {\n            string userChoice;\n            bool loop = false;\n            Console.WriteLine(\"Game over. It took {0} guesses to find the number.\", iterations);\n            while (loop == false)\n            {\n                Console.WriteLine(\"Would you like to play again? {Y/N}\");\n                userChoice = Console.ReadLine();\n                if (userChoice != \"Y\" && userChoice != \"y\" && userChoice != \"N\" && userChoice != \"n\")\n                {\n                    Console.WriteLine(\"Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.\");\n                }\n                if (userChoice == \"Y\" || userChoice == \"y\")\n                {\n                    Start();\n                }\n                if (userChoice == \"N\" || userChoice == \"n\")\n                {\n                    Environment.Exit(1);\n                }\n            }\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = \"Random Number\";\n            RealisticGuess game = new RealisticGuess();\n            game.Start();\n        }\n    }\n}\n"}
{"id": 45359, "name": "Hash from two arrays", "Python": "keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\nhash = {key: value for key, value in zip(keys, values)}\n", "C#": "static class Program\n{\n    static void Main()\n    {\n        System.Collections.Hashtable h = new System.Collections.Hashtable();\n\n        string[] keys = { \"foo\", \"bar\", \"val\" };\n        string[] values = { \"little\", \"miss\", \"muffet\" };\n\n        System.Diagnostics.Trace.Assert(keys.Length == values.Length, \"Arrays are not same length.\");\n\n        for (int i = 0; i < keys.Length; i++)\n        {\n            h.Add(keys[i], values[i]);\n        }\n    }\n}\n"}
{"id": 45360, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 45361, "name": "Bin given limits", "Python": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n    \"Bin data according to (ascending) limits.\"\n    bins = [0] * (len(limits) + 1)      \n    for d in data:\n        bins[bisect_right(limits, d)] += 1\n    return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n    print(f\"          < {limits[0]:3} := {bins[0]:3}\")\n    for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n        print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n    print(f\">= {limits[-1]:3}          := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n    print(\"RC FIRST EXAMPLE\\n\")\n    limits  = [23, 37, 43, 53, 67, 83]\n    data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n\n    print(\"\\nRC SECOND EXAMPLE\\n\")\n    limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n    data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n            416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n            346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,\n            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n            698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n            466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]\n    bins = bin_it(limits, data)\n    bin_print(limits, bins)\n", "C#": "using System;\n\npublic class Program\n{\n    static void Main()\n    {\n        PrintBins(new [] { 23, 37, 43, 53, 67, 83 },\n            95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n            16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55\n        );\n        Console.WriteLine();\n\n        PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },\n            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,\n            253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,\n            622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,\n            945,733,507,916,123,345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,\n            854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,787,942,456,242,759,\n            898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,\n            736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,\n            892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749);\n    }\n\n    static void PrintBins(int[] limits, params int[] data)\n    {\n        int[] bins = Bins(limits, data);\n        Console.WriteLine($\"-∞ .. {limits[0]} => {bins[0]}\");\n        for (int i = 0; i < limits.Length-1; i++) {\n            Console.WriteLine($\"{limits[i]} .. {limits[i+1]} => {bins[i+1]}\");\n        }\n        Console.WriteLine($\"{limits[^1]} .. ∞ => {bins[^1]}\");\n    }\n\n    static int[] Bins(int[] limits, params int[] data)\n    {\n        Array.Sort(limits);\n        int[] bins = new int[limits.Length + 1];\n        foreach (int n in data) {\n            int i = Array.BinarySearch(limits, n);\n            i = i < 0 ? ~i : i+1;\n            bins[i]++;\n        }\n        return bins;\n    }\n}\n"}
{"id": 45362, "name": "Animate a pendulum", "Python": "import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2\n        midtheta = self.theta + (self.dtheta + midDtheta)/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n", "C#": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI / 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width / 2) - 12,\n                anchorY = _form.Height / 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 / _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n"}
{"id": 45363, "name": "Sorting algorithms_Heapsort", "Python": "def heapsort(lst):\n  \n\n  \n  for start in range((len(lst)-2)/2, -1, -1):\n    siftdown(lst, start, len(lst)-1)\n\n  for end in range(len(lst)-1, 0, -1):\n    lst[end], lst[0] = lst[0], lst[end]\n    siftdown(lst, 0, end - 1)\n  return lst\n\ndef siftdown(lst, start, end):\n  root = start\n  while True:\n    child = root * 2 + 1\n    if child > end: break\n    if child + 1 <= end and lst[child] < lst[child + 1]:\n      child += 1\n    if lst[root] < lst[child]:\n      lst[root], lst[child] = lst[child], lst[root]\n      root = child\n    else:\n      break\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HeapSortClass\n{\n    public static void HeapSort<T>(T[] array)\n    {\n        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)\n    {\n        HeapSort<T>(array, offset, length, comparer.Compare);\n    }\n\n    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)\n    {\n        \n        for (int i = 0; i < length; i++)\n        {\n            int index = i;\n            T item = array[offset + i]; \n\n            \n            while (index > 0 &&\n                comparison(array[offset + (index - 1) / 2], item) < 0)\n            {\n                int top = (index - 1) / 2;\n                array[offset + index] = array[offset + top];\n                index = top;\n            }\n            array[offset + index] = item;\n        }\n\n        for (int i = length - 1; i > 0; i--)\n        {\n            \n            T last = array[offset + i];\n            array[offset + i] = array[offset];\n\n            int index = 0;\n            \n            while (index * 2 + 1 < i)\n            {\n                int left = index * 2 + 1, right = left + 1;\n\n                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)\n                {\n                    if (comparison(last, array[offset + right]) > 0) break;\n\n                    array[offset + index] = array[offset + right];\n                    index = right;\n                }\n                else\n                {\n                    if (comparison(last, array[offset + left]) > 0) break;\n\n                    array[offset + index] = array[offset + left];\n                    index = left;\n                }\n            }\n            array[offset + index] = last;\n        }\n    }\n\n    static void Main()\n    {\n        \n        byte[] r = {5, 4, 1, 2};\n        HeapSort(r);\n\n        string[] s = { \"-\", \"D\", \"a\", \"33\" };\n        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);\n    }\n}\n"}
{"id": 45364, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 45365, "name": "Playing cards", "Python": "import random\n\nclass Card(object):\n    suits = (\"Clubs\",\"Hearts\",\"Spades\",\"Diamonds\")\n    pips = (\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"Jack\",\"Queen\",\"King\",\"Ace\")\n\n    def __init__(self, pip,suit):\n        self.pip=pip\n        self.suit=suit\n\n    def __str__(self):\n        return \"%s %s\"%(self.pip,self.suit)\n\nclass Deck(object):\n    def __init__(self):\n        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]\n\n    def __str__(self):\n        return \"[%s]\"%\", \".join( (str(card) for card in self.deck))\n\n    def shuffle(self):\n        random.shuffle(self.deck)\n\n    def deal(self):\n        self.shuffle()  \n        return self.deck.pop(0)\n", "C#": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic struct Card\n{\n    public Card(string rank, string suit) : this()\n    {\n        Rank = rank;\n        Suit = suit;\n    }\n\n    public string Rank { get; }\n    public string Suit { get; }\n\n    public override string ToString() => $\"{Rank} of {Suit}\";\n}\n\npublic class Deck : IEnumerable<Card>\n{\n    static readonly string[] ranks = { \"Two\", \"Three\", \"Four\", \"Five\", \"Six\",\n        \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\" };\n    static readonly string[] suits = { \"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\" };\n    readonly List<Card> cards;\n \n    public Deck() {\n        cards = (from suit in suits\n                from rank in ranks\n                select new Card(rank, suit)).ToList();\n    }\n\n    public int Count => cards.Count;\n\n    public void Shuffle() {\n        \n        var random = new Random();\n        for (int i = 0; i < cards.Count; i++) {\n            int r = random.Next(i, cards.Count);\n            var temp = cards[i];\n            cards[i] = cards[r];\n            cards[r] = temp;\n        }\n    }\n\n    public Card Deal() {\n        int last = cards.Count - 1;\n        Card card = cards[last];\n        \n        \n        cards.RemoveAt(last);\n        return card;\n    }\n\n    public IEnumerator<Card> GetEnumerator() {\n        \n        \n        for (int i = cards.Count - 1; i >= 0; i--)\n            yield return cards[i];\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();\n}\n"}
{"id": 45366, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 45367, "name": "Arrays", "Python": "array = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint array[0]\n", "C#": " int[] numbers = new int[10];\n"}
{"id": 45368, "name": "Sierpinski carpet", "Python": "def setup():\n    size(729, 729)\n    fill(0)\n    background(255)\n    noStroke()\n    rect(width / 3, height / 3, width / 3, width / 3)\n    rectangles(width / 3, height / 3, width / 3)\n\ndef rectangles(x, y, s):\n    if s < 1: return\n    xc, yc = x - s, y - s\n    for row in range(3):\n        for col in range(3):\n            if not (row == 1 and col == 1):\n                xx, yy = xc + row * s, yc + col * s\n                delta = s / 3\n                rect(xx + delta, yy + delta, delta, delta)\n                rectangles(xx + s / 3, yy + s / 3, s / 3)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n"}
{"id": 45369, "name": "Sorting algorithms_Bogosort", "Python": "import random\n\ndef bogosort(l):\n    while not in_order(l):\n        random.shuffle(l)\n    return l\n\ndef in_order(l):\n    if not l:\n        return True\n    last = l[0]\n    for x in l[1:]:\n        if x < last:\n            return False\n        last = x\n    return True\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RosettaCode.BogoSort\n{\n    public static class BogoSorter\n    {\n        public static void Sort<T>(List<T> list) where T:IComparable\n        {\n            while (!list.isSorted())\n            {\n                list.Shuffle();\n            }\n        }\n\n        private static bool isSorted<T>(this IList<T> list) where T:IComparable\n        {\n            if(list.Count<=1)\n                return true;\n            for (int i = 1 ; i < list.Count; i++)\n                if(list[i].CompareTo(list[i-1])<0) return false;\n            return true;\n        }\n\n        private static void Shuffle<T>(this IList<T> list)\n        {\n            Random rand = new Random();\n            for (int i = 0; i < list.Count; i++)\n            {\n                int swapIndex = rand.Next(list.Count);\n                T temp = list[swapIndex];\n                list[swapIndex] = list[i];\n                list[i] = temp;\n            }\n        }\n    }\n\n    class TestProgram\n    {\n        static void Main()\n        {\n            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };\n            BogoSorter.Sort(testList);\n            foreach (int i in testList) Console.Write(i + \" \");\n        }\n\n    }\n}\n"}
{"id": 45370, "name": "Merge and aggregate datasets", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n"}
{"id": 45371, "name": "Merge and aggregate datasets", "Python": "\n\n\nimport pandas as pd\n\n\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n\n\n\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n"}
{"id": 45372, "name": "Euler method", "Python": "def euler(f,y0,a,b,h):\n\tt,y = a,y0\n\twhile t <= b:\n\t\tprint \"%6.3f %6.3f\" % (t,y)\n\t\tt += h\n\t\ty += h * f(t,y)\n\ndef newtoncooling(time, temp):\n\treturn -0.07 * (temp - 20)\n\neuler(newtoncooling,100,0,100,10)\n", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tconst float T0 = 100f;\n\t\tconst float TR = 20f;\n\t\tconst float k = 0.07f;\n\t\treadonly static float[] delta_t = {2.0f,5.0f,10.0f};\n\t\tconst int n = 100;\n\t\t\n\t\tpublic delegate float func(float t);\n\t\tstatic float NewtonCooling(float t)\n\t\t{\n\t\t\treturn -k * (t-TR);\t\t\t\n\t\t}\n\t\t\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfunc f = new func(NewtonCooling); \n\t\t\tfor(int i=0; i<delta_t.Length; i++)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"delta_t = \" + delta_t[i]);\n\t\t\t\tEuler(f,T0,n,delta_t[i]);\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tpublic static void Euler(func f, float y, int n, float h)\n\t\t{\n\t\t\tfor(float x=0; x<=n; x+=h)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"\\t\" + x + \"\\t\" + y);\n\t\t\t\ty += h * f(y);\t\n\t\t\t}\n\t\t}\n\t}\n}\n"}
{"id": 45373, "name": "Sequence of non-squares", "Python": ">>> from math import floor, sqrt\n>>> def non_square(n):\n        return n + floor(1/2 + sqrt(n))\n\n>>> \n>>> print(*map(non_square, range(1, 23)))\n2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27\n\n>>> \n>>> def is_square(n):\n        return sqrt(n).is_integer()\n\n>>> non_squares = map(non_square, range(1, 10 ** 6))\n>>> next(filter(is_square, non_squares))\nStopIteration                             Traceback (most recent call last)\n<ipython-input-45-f32645fc1c0a> in <module>()\n      1 non_squares = map(non_square, range(1, 10 ** 6))\n----> 2 next(filter(is_square, non_squares))\n\nStopIteration:\n", "C#": "using System;\nusing System.Diagnostics;\n\nnamespace sons\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i < 23; i++)            \n                Console.WriteLine(nonsqr(i));            \n\n            for (int i = 1; i < 1000000; i++)\n            {\n                double j = Math.Sqrt(nonsqr(i));\n                Debug.Assert(j != Math.Floor(j),\"Square\");\n            }            \n        }\n\n        static int nonsqr(int i)\n        {\n            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));\n        }\n    }\n}\n"}
{"id": 45374, "name": "Substring", "Python": ">>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> \n>>> s[n-1:n+m-1]\n'bcd'\n>>> \n>>> s[n-1:]\n'bcdefgh'\n>>> \n>>> s[:-1]\n'abcdefg'\n>>> \n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n", "C#": "using System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \n            Console.WriteLine(s.Substring(n, m));\n            \n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n"}
{"id": 45375, "name": "JortSort", "Python": ">>> def jortsort(sequence):\n\treturn list(sequence) == sorted(sequence)\n>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:\n\tprint(f'jortsort({repr(data)}) is {jortsort(data)}')\njortsort((1, 2, 4, 3)) is False\njortsort((14, 6, 8)) is False\njortsort(['a', 'c']) is True\njortsort(['s', 'u', 'x']) is True\njortsort('CVGH') is False\njortsort('PQRST') is True\n>>>\n", "C#": "using System;\n\nclass Program\n{\n  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>\n  {\n    \n    T[] originalArray = (T[]) array.Clone();\n    Array.Sort(array);\n\n    \n    for (var i = 0; i < originalArray.Length; i++)\n    {\n      if (!Equals(originalArray[i], array[i]))\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n"}
{"id": 45376, "name": "Leap year", "Python": "import calendar\ncalendar.isleap(year)\n", "C#": "using System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n"}
{"id": 45377, "name": "Sort numbers lexicographically", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))\n", "C#": "using static System.Console;\nusing static System.Linq.Enumerable;\n\npublic class Program\n{\n    public static void Main() {\n        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($\"{n}: {string.Join(\", \", LexOrder(n))}\");\n    }\n\n    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());\n}\n"}
{"id": 45378, "name": "Number names", "Python": "TENS = [None, None, \"twenty\", \"thirty\", \"forty\",\n        \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\nSMALL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n         \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n         \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n         \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\nHUGE = [None, None] + [h + \"illion\" \n                       for h in (\"m\", \"b\", \"tr\", \"quadr\", \"quint\", \"sext\", \n                                  \"sept\", \"oct\", \"non\", \"dec\")]\n\ndef nonzero(c, n, connect=''):\n    return \"\" if n == 0 else connect + c + spell_integer(n)\n\ndef last_and(num):\n    if ',' in num:\n        pre, last = num.rsplit(',', 1)\n        if ' and ' not in last:\n            last = ' and' + last\n        num = ''.join([pre, ',', last])\n    return num\n    \ndef big(e, n):\n    if e == 0:\n        return spell_integer(n)\n    elif e == 1:\n        return spell_integer(n) + \" thousand\"\n    else:\n        return spell_integer(n) + \" \" + HUGE[e]\n\ndef base1000_rev(n):\n    \n    \n    while n != 0:\n        n, r = divmod(n, 1000)\n        yield r\n \ndef spell_integer(n):\n    if n < 0:\n        return \"minus \" + spell_integer(-n)\n    elif n < 20:\n        return SMALL[n]\n    elif n < 100:\n        a, b = divmod(n, 10)\n        return TENS[a] + nonzero(\"-\", b)\n    elif n < 1000:\n        a, b = divmod(n, 100)\n        return SMALL[a] + \" hundred\" + nonzero(\" \", b, ' and')\n    else:\n        num = \", \".join([big(e, x) for e, x in\n                         enumerate(base1000_rev(n)) if x][::-1])\n        return last_and(num)\n\nif __name__ == '__main__':\n    \n    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):\n        print('%+4i -> %s' % (n, spell_integer(n)))\n    print('')  \n    \n    n = 201021002001\n    while n:\n        print('%-12i -> %s' % (n, spell_integer(n)))\n        n //= -10\n    print('%-12i -> %s' % (n, spell_integer(n)))\n    print('')\n", "C#": "using System;\n\nclass NumberNamer {\n    static readonly string[] incrementsOfOne =\n            { \"zero\",    \"one\",     \"two\",       \"three\",    \"four\",\n              \"five\",    \"six\",     \"seven\",     \"eight\",    \"nine\",\n              \"ten\",     \"eleven\",  \"twelve\",    \"thirteen\", \"fourteen\",\n              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n    static readonly string[] incrementsOfTen =\n            { \"\",      \"\",      \"twenty\",  \"thirty\", \"fourty\",\n              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n    const string millionName = \"million\",\n                 thousandName = \"thousand\",\n                 hundredName = \"hundred\",\n                 andName = \"and\";\n\n\n    public static string GetName( int i ) {\n        string output = \"\";\n        if( i >= 1000000 ) {\n            output += ParseTriplet( i / 1000000 ) + \" \" + millionName;\n            i %= 1000000;\n            if( i == 0 ) return output;\n        }\n\n        if( i >= 1000 ) {\n            if( output.Length > 0 ) {\n                output += \", \";\n            }\n            output += ParseTriplet( i / 1000 ) + \" \" + thousandName;\n            i %= 1000;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \", \";\n        }\n        output += ParseTriplet( i );\n        return output;\n    }\n\n\n    static string ParseTriplet( int i ) {\n        string output = \"\";\n        if( i >= 100 ) {\n            output += incrementsOfOne[i / 100] + \" \" + hundredName;\n            i %= 100;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \" + andName + \" \";\n        }\n        if( i >= 20 ) {\n            output += incrementsOfTen[i / 10];\n            i %= 10;\n            if( i == 0 ) return output;\n        }\n\n        if( output.Length > 0 ) {\n            output += \" \";\n        }\n        output += incrementsOfOne[i];\n        return output;\n    }\n}\n\n\nclass Program { \n    static void Main( string[] args ) {\n        Console.WriteLine( NumberNamer.GetName( 1 ) );\n        Console.WriteLine( NumberNamer.GetName( 234 ) );\n        Console.WriteLine( NumberNamer.GetName( 31337 ) );\n        Console.WriteLine( NumberNamer.GetName( 987654321 ) );\n    }\n}\n"}
{"id": 45379, "name": "Compare length of two strings", "Python": "A = 'I am string'\nB = 'I am string too'\n\nif len(A) > len(B):\n    print('\"' + A + '\"', 'has length', len(A), 'and is the longest of the two strings')\n    print('\"' + B + '\"', 'has length', len(B), 'and is the shortest of the two strings')\nelif len(A) < len(B):\n    print('\"' + B + '\"', 'has length', len(B), 'and is the longest of the two strings')\n    print('\"' + A + '\"', 'has length', len(A), 'and is the shortest of the two strings')\nelse:\n    print('\"' + A + '\"', 'has length', len(A), 'and it is as long as the second string')\n    print('\"' + B + '\"', 'has length', len(B), 'and it is as long as the second string')\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace example\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var strings = new string[] { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n            compareAndReportStringsLength(strings);\n        }\n\n        private static void compareAndReportStringsLength(string[] strings)\n        {\n            if (strings.Length > 0)\n            {\n                char Q = '\"';\n                string hasLength = \" has length \";\n                string predicateMax = \" and is the longest string\";\n                string predicateMin = \" and is the shortest string\";\n                string predicateAve = \" and is neither the longest nor the shortest string\";\n                string predicate;\n\n                (int, int)[] li = new (int, int)[strings.Length];\n                for (int i = 0; i < strings.Length; i++)\n                    li[i] = (strings[i].Length, i);\n                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);\n                int maxLength = li[0].Item1;\n                int minLength = li[strings.Length - 1].Item1;\n\n                for (int i = 0; i < strings.Length; i++)\n                {\n                    int length = li[i].Item1;\n                    string str = strings[li[i].Item2];\n                    if (length == maxLength)\n                        predicate = predicateMax;\n                    else if (length == minLength)\n                        predicate = predicateMin;\n                    else\n                        predicate = predicateAve;\n                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);\n                }\n            }\n        }\n\n    }\n}\n"}
{"id": 45380, "name": "Letter frequency", "Python": "import collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n"}
{"id": 45381, "name": "Increment a numerical string", "Python": "next = str(int('123') + 1)\n", "C#": "string s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\n\n\n\n\n\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\n\n"}
{"id": 45382, "name": "Strip a set of characters from a string", "Python": ">>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n", "C#": "using System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n"}
{"id": 45383, "name": "Averages_Arithmetic mean", "Python": "from math import fsum\ndef average(x):\n    return fsum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))\n", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(new[] { 1, 2, 3 }.Average());\n    }\n}\n"}
{"id": 45384, "name": "Entropy", "Python": "from __future__ import division\nimport math\n\ndef hist(source):\n    hist = {}; l = 0;\n    for e in source:\n        l += 1\n        if e not in hist:\n            hist[e] = 0\n        hist[e] += 1\n    return (l,hist)\n\ndef entropy(hist,l):\n    elist = []\n    for v in hist.values():\n        c = v / l\n        elist.append(-c * math.log(c ,2))\n    return sum(elist)\n\ndef printHist(h):\n    flip = lambda (k,v) : (v,k)\n    h = sorted(h.iteritems(), key = flip)\n    print 'Sym\\thi\\tfi\\tInf'\n    for (k,v) in h:\n        print '%s\\t%f\\t%f\\t%f'%(k,v,v/l,-math.log(v/l, 2))\n    \n    \n\nsource = \"1223334444\"\n(l,h) = hist(source);\nprint '.[Results].'\nprint 'Length',l\nprint 'Entropy:', entropy(h, l)\nprintHist(h)\n", "C#": "using System;\nusing System.Collections.Generic;\nnamespace Entropy\n{\n\tclass Program\n\t{\n\t\tpublic static double logtwo(double num)\n\t\t{\n\t\t\treturn Math.Log(num)/Math.Log(2);\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\tlabel1:\n\t\t\tstring input = Console.ReadLine();\n\t\t\tdouble infoC=0;\n\t\t\tDictionary<char,double> table = new Dictionary<char, double>();\n\n\t\t\t\n\t\t\tforeach (char c in input)\n\t\t\t{\n\t\t\t\tif (table.ContainsKey(c))\n\t\t\t\t\ttable[c]++;\n\t\t\t\t    else\n\t\t\t\t    \ttable.Add(c,1);\n\t\n\t\t\t}\n\t\t\tdouble freq;\n\t\t\tforeach (KeyValuePair<char,double> letter in table)\n\t\t\t{\n\t\t\t\tfreq=letter.Value/input.Length;\n\t\t\t\tinfoC+=freq*logtwo(freq);\n\t\t\t}\n\t\t\tinfoC*=-1;\n\t\t\tConsole.WriteLine(\"The Entropy of {0} is {1}\",input,infoC);\n\t\t\tgoto label1;\n\t\t\n\t\t}\n\t}\n}\n"}
{"id": 45385, "name": "Tokenize a string with escaping", "Python": "def token_with_escape(a, escape = '^', separator = '|'):\n    \n    result = []\n    token = ''\n    state = 0\n    for c in a:\n        if state == 0:\n            if c == escape:\n                state = 1\n            elif c == separator:\n                result.append(token)\n                token = ''\n            else:\n                token += c\n        elif state == 1:\n            token += c\n            state = 0\n    result.append(token)\n    return result\n", "C#": "using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class TokenizeAStringWithEscaping\n{\n    public static void Main() {\n        string testcase = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {\n            Console.WriteLine(\": \" + token); \n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {\n        if (input == null) yield break;\n        var buffer = new StringBuilder();\n        bool escaping = false;\n        foreach (char c in input) {\n            if (escaping) {\n                buffer.Append(c);\n                escaping = false;\n            } else if (c == escape) {\n                escaping = true;\n            } else if (c == separator) {\n                yield return buffer.Flush();\n            } else {\n                buffer.Append(c);\n            }\n        }\n        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();\n    }\n    \n    public static string Flush(this StringBuilder stringBuilder) {\n        string result = stringBuilder.ToString();\n        stringBuilder.Clear();\n        return result;\n    }\n}\n"}
{"id": 45386, "name": "Hello world_Text", "Python": "print \"Hello world!\"\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 45387, "name": "Hello world_Text", "Python": "print \"Hello world!\"\n", "C#": "Using System;\nnamespace HelloWorld {\n  class Program\n  {\n    static void Main()\n    {\n      Console.Writeln(\"Hello World!\");\n    }\n  }\n}\n"}
{"id": 45388, "name": "Forward difference", "Python": ">>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]\n>>> \n>>> difn = lambda s, n: difn(dif(s), n-1) if n else s\n\n>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 0)\n[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\n>>> difn(s, 1)\n[-43, 11, -29, -7, 10, 23, -50, 50, 18]\n>>> difn(s, 2)\n[54, -40, 22, 17, 13, -73, 100, -32]\n\n>>> from pprint import pprint\n>>> pprint( [difn(s, i) for i in xrange(10)] )\n[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],\n [-43, 11, -29, -7, 10, 23, -50, 50, 18],\n [54, -40, 22, 17, 13, -73, 100, -32],\n [-94, 62, -5, -4, -86, 173, -132],\n [156, -67, 1, -82, 259, -305],\n [-223, 68, -83, 341, -564],\n [291, -151, 424, -905],\n [-442, 575, -1329],\n [1017, -1904],\n [-2921]]\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)\n    {\n        switch (order)\n        {\n            case 0u:\n                return sequence;\n            case 1u:\n                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);\n            default:\n                return ForwardDifference(ForwardDifference(sequence), order - 1u);\n        }\n    }\n\n    static void Main()\n    {\n        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };\n        do\n        {\n            Console.WriteLine(string.Join(\", \", sequence));\n        } while ((sequence = ForwardDifference(sequence)).Any());\n    }\n}\n"}
{"id": 45389, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 45390, "name": "Primality by trial division", "Python": "def prime(a):\n    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n", "C#": "static bool isPrime(int n)\n        {\n            if (n <= 1) return false;\n            for (int i = 2; i * i <= n; i++)            \n                if (n % i == 0) return false;            \n            return true;\n        }\n"}
{"id": 45391, "name": "Evaluate binomial coefficients", "Python": "def binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) / i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n", "C#": "using System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c / (i + 1);\n            }\n            return c;\n        }\n    }\n}\n"}
{"id": 45392, "name": "Collections", "Python": "collection = [0, '1']                 \nx = collection[0]                     \ncollection.append(2)                  \ncollection.insert(0, '-1')            \ny = collection[0]                     \ncollection.extend([2,'3'])            \ncollection += [2,'3']                 \ncollection[2:6]                       \nlen(collection)                       \ncollection = (0, 1)                   \ncollection[:]                         \ncollection[-4:-1]                     \ncollection[::2]                       \ncollection=\"some string\"              \nx = collection[::-1]                  \ncollection[::2] == \"some string\"[::2] \ncollection.__getitem__(slice(0,len(collection),2))  \ncollection = {0: \"zero\", 1: \"one\"}    \ncollection['zero'] = 2                \ncollection = set([0, '1'])            \n", "C#": "\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n"}
{"id": 45393, "name": "Singly-linked list_Traversal", "Python": "for node in lst:\n    print node.value\n", "C#": "var current = [head of list to traverse]\nwhile(current != null)\n{\n    \n\n    current = current.Next;\n}\n"}
{"id": 45394, "name": "Bitmap_Write a PPM file", "Python": "\nimport io\nppmfileout = io.StringIO('')\n\ndef writeppmp3(self, f):\n    self.writeppm(f, ppmformat='P3')\n        \ndef writeppm(self, f, ppmformat='P6'):\n    assert ppmformat in ['P3', 'P6'], 'Format wrong'\n    magic = ppmformat + '\\n'\n    comment = '\n    maxval = max(max(max(bit) for bit in row) for row in self.map)\n    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'\n    if ppmformat == 'P6':\n        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))\n        maxval = 255\n    else:\n        fwrite = f.write\n        numsize=len(str(maxval))\n    fwrite(magic)\n    fwrite(comment)\n    fwrite('%i %i\\n%i\\n' % (self.width, self.height, maxval))\n    for h in range(self.height-1, -1, -1):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            if ppmformat == 'P3':\n                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))\n            else:\n                fwrite('%c%c%c' % (r, g, b))\n        if ppmformat == 'P3':\n            fwrite('\\n')\n\nBitmap.writeppmp3 = writeppmp3\nBitmap.writeppm = writeppm\n\n\nbitmap = Bitmap(4, 4, black)\nbitmap.fillrect(1, 0, 1, 2, white)\nbitmap.set(3, 3, Colour(127, 0, 63))\n\nbitmap.writeppmp3(ppmfileout)\n\nprint(ppmfileout.getvalue())\n\n\n\n\nppmfileout = open('tmp.ppm', 'wb')\nbitmap.writeppm(ppmfileout)\nppmfileout.close()\n", "C#": "using System;\nusing System.IO;\nclass PPMWriter\n{\n    public static void WriteBitmapToPPM(string file, Bitmap bitmap)\n        {\n            \n            var writer = new StreamWriter(file);\n            writer.WriteLine(\"P6\");\n            writer.WriteLine($\"{bitmap.Width}  {bitmap.Height}\");\n            writer.WriteLine(\"255\");\n            writer.Close();\n            \n            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));\n            for (int x = 0; x < bitmap.Height; x++)\n                for (int y = 0; y < bitmap.Width; y++)\n                {\n                    Color color = bitmap.GetPixel(y, x);\n                    writerB.Write(color.R);\n                    writerB.Write(color.G);\n                    writerB.Write(color.B);\n                }\n            writerB.Close();\n        }\n}\n"}
{"id": 45395, "name": "Delete a file", "Python": "import os\n\nos.remove(\"output.txt\")\nos.rmdir(\"docs\")\n\nos.remove(\"/output.txt\")\nos.rmdir(\"/docs\")\n", "C#": "using System;\nusing System.IO;\n\nnamespace DeleteFile {\n  class Program {\n    static void Main() {\n      File.Delete(\"input.txt\");\n      Directory.Delete(\"docs\");\n      File.Delete(\"/input.txt\");\n      Directory.Delete(\"/docs\");\n    }\n  }\n}\n"}
{"id": 45396, "name": "Discordian date", "Python": "import datetime, calendar\n\nDISCORDIAN_SEASONS = [\"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"]\n\ndef ddate(year, month, day):\n    today = datetime.date(year, month, day)\n    is_leap_year = calendar.isleap(year)\n    if is_leap_year and month == 2 and day == 29:\n        return \"St. Tib's Day, YOLD \" + (year + 1166)\n    \n    day_of_year = today.timetuple().tm_yday - 1\n    \n    if is_leap_year and day_of_year >= 60:\n        day_of_year -= 1 \n    \n    season, dday = divmod(day_of_year, 73)\n    return \"%s %d, YOLD %d\" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)\n", "C#": "using System;\n\npublic static class DiscordianDate\n{\n    static readonly string[] seasons = { \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\" };\n    static readonly string[] weekdays = { \"Sweetmorn\", \"Boomtime\", \"Pungenday\", \"Prickle-Prickle\", \"Setting Orange\" };\n    static readonly string[] apostles = { \"Mungday\", \"Mojoday\", \"Syaday\", \"Zaraday\", \"Maladay\" };\n    static readonly string[] holidays = { \"Chaoflux\", \"Discoflux\", \"Confuflux\", \"Bureflux\", \"Afflux\" };\n    \n    public static string Discordian(this DateTime date) {\n        string yold = $\" in the YOLD {date.Year + 1166}.\";\n        int dayOfYear = date.DayOfYear;\n\n        if (DateTime.IsLeapYear(date.Year)) {\n            if (dayOfYear == 60) return \"St. Tib's day\" + yold;\n            else if (dayOfYear > 60) dayOfYear--;\n        }\n        dayOfYear--;\n\n        int seasonDay = dayOfYear % 73 + 1;\n        int seasonNr = dayOfYear / 73;\n        int weekdayNr = dayOfYear % 5;\n        string holyday = \"\";\n\n        if (seasonDay == 5)       holyday = $\" Celebrate {apostles[seasonNr]}!\";\n        else if (seasonDay == 50) holyday = $\" Celebrate {holidays[seasonNr]}!\";\n        return $\"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}\";\n    }\n\n    public static void Main() {\n        foreach (var (day, month, year) in new [] {\n            (1, 1, 2010),\n            (5, 1, 2010),\n            (19, 2, 2011),\n            (28, 2, 2012),\n            (29, 2, 2012),\n            (1, 3, 2012),\n            (19, 3, 2013),\n            (3, 5, 2014),\n            (31, 5, 2015),\n            (22, 6, 2016),\n            (15, 7, 2016),\n            (12, 8, 2017),\n            (19, 9, 2018),\n            (26, 9, 2018),\n            (24, 10, 2019),\n            (8, 12, 2020),\n            (31, 12, 2020)\n        })\n        {\n            Console.WriteLine($\"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}\");\n        }\n    }\n\n}\n"}
{"id": 45397, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 45398, "name": "Average loop length", "Python": "from __future__ import division \nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n    count = 0\n    for i in range(times):\n        x, bits = 1, 0\n        while not (bits & x):\n            count += 1\n            bits |= x\n            x = 1 << randrange(n)\n    return count / times\n\nif __name__ == '__main__':\n    print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n    for n in range(1, MAX_N+1):\n        avg = test(n, TIMES)\n        theory = analytical(n)\n        diff = (avg / theory - 1) * 100\n        print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))\n", "C#": "public class AverageLoopLength {\n\tprivate static int N = 100000;\n\t\n\tprivate static double analytical(int n) {\n\t\tdouble[] factorial = new double[n + 1];\n\t\tdouble[] powers = new double[n + 1];\n\t\tpowers[0] = 1.0;\n\t\tfactorial[0] = 1.0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfactorial[i] = factorial[i - 1] * i;\n\t\t\tpowers[i] = powers[i - 1] * n;\n\t\t}\n\t\tdouble sum = 0;\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tsum += factorial[n] / factorial[n - i] / powers[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static double average(int n) {\n\t\tRandom rnd = new Random();\n\t\tdouble sum = 0.0;\n\t\tfor (int a = 0; a < N; a++) {\n\t\t\tint[] random = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\trandom[i] = rnd.Next(n);\n\t\t\t}\n\t\t\tvar seen = new HashSet<double>(n);\n\t\t\tint current = 0;\n\t\t\tint length = 0;\n\t\t\twhile (seen.Add(current)) {\n\t\t\t\tlength++;\n\t\t\t\tcurrent = random[current];\n\t\t\t}\n\t\t\tsum += length;\n\t\t}\n\t\treturn sum / N;\n\t}\n\t\n\tpublic static void Main(string[] args) {\n\tConsole.WriteLine(\" N    average    analytical    (error)\");\n\tConsole.WriteLine(\"===  =========  ============  =========\");\n\t\tfor (int i = 1; i <= 20; i++) {\n\t\t\tvar average = AverageLoopLength.average(i);\n\t\t\tvar analytical = AverageLoopLength.analytical(i);\n\t\t\tConsole.WriteLine(\"{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%\", i, average, analytical, (analytical - average) / analytical * 100);\n\t\t}\n\t}\n}\n"}
{"id": 45399, "name": "String interpolation (included)", "Python": ">>> original = 'Mary had a %s lamb.'\n>>> extra = 'little'\n>>> original % extra\n'Mary had a little lamb.'\n", "C#": "class Program\n{\n    static void Main()\n    {\n        string extra = \"little\";\n        string formatted = $\"Mary had a {extra} lamb.\";\n        System.Console.WriteLine(formatted);\n    }\n}\n"}
{"id": 45400, "name": "Partition function P", "Python": "from itertools import islice\n\ndef posd():\n    \"diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7...\"\n    count, odd = 1, 3\n    while True:\n        yield count\n        yield odd\n        count, odd = count + 1, odd + 2\n\ndef pos_gen():\n    \"position numbers. 1 3 2 5 7 4 9 ...\"\n    val = 1\n    diff = posd()\n    while True:\n        yield val\n        val += next(diff)\n                \ndef plus_minus():\n    \"yield (list_offset, sign) or zero for Partition calc\"\n    n, sign = 0, [1, 1]\n    p_gen = pos_gen()\n    out_on = next(p_gen)\n    while True:\n        n += 1\n        if n == out_on:\n            next_sign = sign.pop(0)\n            if not sign:\n                sign = [-next_sign] * 2\n            yield -n, next_sign\n            out_on = next(p_gen)\n        else:\n            yield 0\n            \ndef part(n):\n    \"Partition numbers\"\n    p = [1]\n    p_m = plus_minus()\n    mods = []\n    for _ in range(n):\n        next_plus_minus = next(p_m)\n        if next_plus_minus:\n            mods.append(next_plus_minus)\n        p.append(sum(p[offset] * sign for offset, sign in mods))\n    return p[-1]\n        \nprint(\"(Intermediaries):\")\nprint(\"    posd:\", list(islice(posd(), 10)))\nprint(\"    pos_gen:\", list(islice(pos_gen(), 10)))\nprint(\"    plus_minus:\", list(islice(plus_minus(), 15)))\nprint(\"\\nPartitions:\", [part(x) for x in range(15)])\n", "C#": "using System;\n\nclass Program {\n\n    const long Lm = (long)1e18;\n    const string Fm = \"D18\";\n\n    \n    struct LI { public long lo, ml, mh, hi, tp; }\n\n    static void inc(ref LI d, LI s) { \n        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }\n        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }\n        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }\n        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }\n        d.tp += s.tp;\n    }\n \n    static void dec(ref LI d, LI s) { \n        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }\n        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }\n        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }\n        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }\n        d.tp -= s.tp;\n    }\n\n    static LI set(long s) { LI d;\n      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }\n\n  static string fmt(LI x) { \n    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);\n    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);\n    return x.lo.ToString();\n  }\n\n  static LI partcount(int n) {\n    var P = new LI[n + 1]; P[0] = set(1);\n    for (int i = 1; i <= n; i++) {\n      int k = 0, d = -2, j = i;\n      LI x = set(0);\n      while (true) {\n        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;\n        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;\n        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;\n      }\n      P[i] = x;\n    }\n    return P[n];\n  }\n\n  static void Main(string[] args) {\n    var sw = System.Diagnostics.Stopwatch.StartNew ();\n    var res = partcount(6666); sw.Stop();\n    Console.Write(\"{0}  {1} ms\", fmt(res), sw.Elapsed.TotalMilliseconds);\n  }\n}\n"}
{"id": 45401, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 45402, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 45403, "name": "Numbers with prime digits whose sum is 13", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n    q = deque([(r, 0)])\n    while q:\n        r, n = q.popleft()\n        for d in 2, 3, 5, 7:\n            if d >= r:\n                if d == r: yield n + d\n                break\n            q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))\n", "C#": "using System;\nusing static System.Console; \nusing LI = System.Collections.Generic.SortedSet<int>;\n\nclass Program {\n\n  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {\n    if (lft == 0) res.Add(vlu);\n    else if (lft > 0) foreach (int itm in set)\n      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);\n    return res; }\n\n  static void Main(string[] args) { WriteLine(string.Join(\" \",\n      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }\n}\n"}
{"id": 45404, "name": "Take notes on the command line", "Python": "import sys, datetime, shutil\n\nif len(sys.argv) == 1:\n    try:\n        with open('notes.txt', 'r') as f:\n            shutil.copyfileobj(f, sys.stdout)\n    except IOError:\n        pass\nelse:\n    with open('notes.txt', 'a') as f:\n        f.write(datetime.datetime.now().isoformat() + '\\n')\n        f.write(\"\\t%s\\n\" % ' '.join(sys.argv[1:]))\n", "C#": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace RosettaCode\n{\n  internal class Program\n  {\n    private const string FileName = \"NOTES.TXT\";\n\n    private static void Main(string[] args)\n    {\n      if (args.Length==0)\n      {\n        string txt = File.ReadAllText(FileName);\n        Console.WriteLine(txt);\n      }\n      else\n      {\n        var sb = new StringBuilder();\n        sb.Append(DateTime.Now).Append(\"\\n\\t\");\n        foreach (string s in args)\n          sb.Append(s).Append(\" \");\n        sb.Append(\"\\n\");\n\n        if (File.Exists(FileName))\n          File.AppendAllText(FileName, sb.ToString());\n        else\n          File.WriteAllText(FileName, sb.ToString());\n      }\n    }\n  }\n}\n"}
{"id": 45405, "name": "Angles (geometric), normalization and conversion", "Python": "PI = 3.141592653589793\nTWO_PI = 6.283185307179586\n\ndef normalize2deg(a):\n  while a < 0: a += 360\n  while a >= 360: a -= 360\n  return a\ndef normalize2grad(a):\n  while a < 0: a += 400\n  while a >= 400: a -= 400\n  return a\ndef normalize2mil(a):\n  while a < 0: a += 6400\n  while a >= 6400: a -= 6400\n  return a\ndef normalize2rad(a):\n  while a < 0: a += TWO_PI\n  while a >= TWO_PI: a -= TWO_PI\n  return a\n\ndef deg2grad(a): return a * 10.0 / 9.0\ndef deg2mil(a): return a * 160.0 / 9.0\ndef deg2rad(a): return a * PI / 180.0\n\ndef grad2deg(a): return a * 9.0 / 10.0\ndef grad2mil(a): return a * 16.0\ndef grad2rad(a): return a * PI / 200.0\n\ndef mil2deg(a): return a * 9.0 / 160.0\ndef mil2grad(a): return a / 16.0\ndef mil2rad(a): return a * PI / 3200.0\n\ndef rad2deg(a): return a * 180.0 / PI\ndef rad2grad(a): return a * 200.0 / PI\ndef rad2mil(a): return a * 3200.0 / PI\n", "C#": "using System;\n\npublic static class Angles\n{\n    public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);\n\n    public static void Print(params double[] angles) {\n        string[] names = { \"Degrees\", \"Gradians\", \"Mils\", \"Radians\" };\n        Func<double, double> rnd = a => Math.Round(a, 4);\n        Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };\n\n        Func<double, double>[,] convert = {\n            { a => a, DegToGrad, DegToMil, DegToRad },\n            { GradToDeg, a => a, GradToMil, GradToRad },\n            { MilToDeg, MilToGrad, a => a, MilToRad },\n            { RadToDeg, RadToGrad, RadToMil, a => a }\n        };\n\n        Console.WriteLine($@\"{\"Angle\",-12}{\"Normalized\",-12}{\"Unit\",-12}{\n            \"Degrees\",-12}{\"Gradians\",-12}{\"Mils\",-12}{\"Radians\",-12}\");\n\n        foreach (double angle in angles) {\n            for (int i = 0; i < 4; i++) {\n                double nAngle = normal[i](angle);\n\n                Console.WriteLine($@\"{\n                    rnd(angle),-12}{\n                    rnd(nAngle),-12}{\n                    names[i],-12}{\n                    rnd(convert[i, 0](nAngle)),-12}{\n                    rnd(convert[i, 1](nAngle)),-12}{\n                    rnd(convert[i, 2](nAngle)),-12}{\n                    rnd(convert[i, 3](nAngle)),-12}\");\n            }\n        }\n    }\n\n    public static double NormalizeDeg(double angle) => Normalize(angle, 360);\n    public static double NormalizeGrad(double angle) => Normalize(angle, 400);\n    public static double NormalizeMil(double angle) => Normalize(angle, 6400);\n    public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);\n\n    private static double Normalize(double angle, double N) {\n        while (angle <= -N) angle += N;\n        while (angle >= N) angle -= N;\n        return angle;\n    }\n\n    public static double DegToGrad(double angle) => angle * 10 / 9;\n    public static double DegToMil(double angle) => angle * 160 / 9;\n    public static double DegToRad(double angle) => angle * Math.PI / 180;\n    \n    public static double GradToDeg(double angle) => angle * 9 / 10;\n    public static double GradToMil(double angle) => angle * 16;\n    public static double GradToRad(double angle) => angle * Math.PI / 200;\n    \n    public static double MilToDeg(double angle) => angle * 9 / 160;\n    public static double MilToGrad(double angle) => angle / 16;\n    public static double MilToRad(double angle) => angle * Math.PI / 3200;\n    \n    public static double RadToDeg(double angle) => angle * 180 / Math.PI;\n    public static double RadToGrad(double angle) => angle * 200 / Math.PI;\n    public static double RadToMil(double angle) => angle * 3200 / Math.PI;\n}\n"}
{"id": 45406, "name": "Find common directory path", "Python": ">>> import os\n>>> os.path.commonpath(['/home/user1/tmp/coverage/test', \n                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])\n'/home/user1/tmp'\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coverage/test\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/covert/operator\" );\n\t\t\tPathSet1.Add ( \"/home/user1/tmp/coven/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n"}
{"id": 45407, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 45408, "name": "Recaman's sequence", "Python": "from itertools import islice\n\nclass Recamans():\n    \"Recamán's sequence generator callable class\"\n    def __init__(self):\n        self.a = None   \n        self.n = None   \n    \n    def __call__(self):\n        \"Recamán's sequence  generator\"\n        nxt = 0\n        a, n = {nxt}, 0\n        self.a = a\n        self.n = n\n        yield nxt\n        while True:\n            an1, n = nxt, n + 1\n            nxt = an1 - n\n            if nxt < 0 or nxt in a:\n                nxt = an1 + n\n            a.add(nxt)\n            self.n = n\n            yield nxt\n\nif __name__ == '__main__':\n    recamans = Recamans()\n    print(\"First fifteen members of Recamans sequence:\", \n          list(islice(recamans(), 15)))\n\n    so_far = set()\n    for term in recamans():\n        if term in so_far:\n            print(f\"First duplicate number in series is: a({recamans.n}) = {term}\")\n            break\n        so_far.add(term)\n    \n    n = 1_000\n    setn = set(range(n + 1))    \n    for _ in recamans():\n        if setn.issubset(recamans.a):\n            print(f\"Range 0 ..{n} is covered by terms up to a({recamans.n})\")\n            break\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace RecamanSequence {\n    class Program {\n        static void Main(string[] args) {\n            List<int> a = new List<int>() { 0 };\n            HashSet<int> used = new HashSet<int>() { 0 };\n            HashSet<int> used1000 = new HashSet<int>() { 0 };\n            bool foundDup = false;\n            int n = 1;\n            while (n <= 15 || !foundDup || used1000.Count < 1001) {\n                int next = a[n - 1] - n;\n                if (next < 1 || used.Contains(next)) {\n                    next += 2 * n;\n                }\n                bool alreadyUsed = used.Contains(next);\n                a.Add(next);\n                if (!alreadyUsed) {\n                    used.Add(next);\n                    if (0 <= next && next <= 1000) {\n                        used1000.Add(next);\n                    }\n                }\n                if (n == 14) {\n                    Console.WriteLine(\"The first 15 terms of the Recaman sequence are: [{0}]\", string.Join(\", \", a));\n                }\n                if (!foundDup && alreadyUsed) {\n                    Console.WriteLine(\"The first duplicated term is a[{0}] = {1}\", n, next);\n                    foundDup = true;\n                }\n                if (used1000.Count == 1001) {\n                    Console.WriteLine(\"Terms up to a[{0}] are needed to generate 0 to 1000\", n);\n                }\n                n++;\n            }\n        }\n    }\n}\n"}
{"id": 45409, "name": "Memory allocation", "Python": ">>> from array import array\n>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \\u2641'),\n\t('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]\n>>> for typecode, initializer in argslist:\n\ta = array(typecode, initializer)\n\tprint a\n\tdel a\n\n\t\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.1400000000000001])\n>>>\n", "C#": "using System;\nusing System.Runtime.InteropServices;\n\npublic unsafe class Program\n{\n    public static unsafe void HeapMemory()\n    {\n        const int HEAP_ZERO_MEMORY = 0x00000008;\n        const int size = 1000;\n        int ph = GetProcessHeap();\n        void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);\n        if (pointer == null)\n            throw new OutOfMemoryException();\n        Console.WriteLine(HeapSize(ph, 0, pointer));\n        HeapFree(ph, 0, pointer);\n    }\n\n    public static unsafe void StackMemory()\n    {\n        byte* buffer = stackalloc byte[1000];\n        \n    }\n    public static void Main(string[] args)\n    {\n        HeapMemory();\n        StackMemory();\n    }\n    [DllImport(\"kernel32\")]\n    static extern void* HeapAlloc(int hHeap, int flags, int size);\n    [DllImport(\"kernel32\")]\n    static extern bool HeapFree(int hHeap, int flags, void* block);\n    [DllImport(\"kernel32\")]\n    static extern int GetProcessHeap();\n    [DllImport(\"kernel32\")]\n    static extern int HeapSize(int hHeap, int flags, void* block);\n\n}\n"}
{"id": 45410, "name": "Tic-tac-toe", "Python": "\n\nimport random\n\nboard = list('123456789')\nwins = ((0,1,2), (3,4,5), (6,7,8),\n        (0,3,6), (1,4,7), (2,5,8),\n        (0,4,8), (2,4,6))\n\ndef printboard():\n    print('\\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))\n\ndef score():\n    for w in wins:\n        b = board[w[0]]\n        if b in 'XO' and all (board[i] == b for i in w):\n            return b, [i+1 for i in w]\n    return None, None\n\ndef finished():\n    return all (b in 'XO' for b in board)\n\ndef space():\n    return [ b for b in board if b not in 'XO']\n\ndef my_turn(xo):\n    options = space()\n    choice = random.choice(options)\n    board[int(choice)-1] = xo\n    return choice\n\ndef your_turn(xo):\n    options = space()\n    while True:\n        choice = input(\" Put your %s in any of these positions: %s \"\n                       % (xo, ''.join(options))).strip()\n        if choice in options:\n            break\n        print( \"Whoops I don't understand the input\" )\n    board[int(choice)-1] = xo\n    return choice\n\ndef me(xo='X'):\n    printboard()\n    print('I go at', my_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\ndef you(xo='O'):\n    printboard()\n    \n    print('You went at', your_turn(xo))\n    return score()\n    assert not s[0], \"\\n%s wins across %s\" % s\n\n\nprint(__doc__)\nwhile not finished():\n    s = me('X')\n    if s[0]:\n        printboard()\n        print(\"\\n%s wins across %s\" % s)\n        break\n    if not finished():\n        s = you('O')\n        if s[0]:\n            printboard()\n            print(\"\\n%s wins across %s\" % s)\n            break\nelse:\n    print('\\nA draw')\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaTicTacToe\n{\n  class Program\n  {\n\n    \n    static string[][] Players = new string[][] { \n      new string[] { \"COMPUTER\", \"X\" }, \n      new string[] { \"HUMAN\", \"O\" }     \n    };\n\n    const int Unplayed = -1;\n    const int Computer = 0;\n    const int Human = 1;\n\n    \n    static int[] GameBoard = new int[9];\n\n    static int[] corners = new int[] { 0, 2, 6, 8 };\n\n    static int[][] wins = new int[][] { \n      new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, \n      new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, \n      new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };\n\n\n    \n    static void Main(string[] args)\n    {\n      while (true)\n      {\n        Console.Clear();\n        Console.WriteLine(\"Welcome to Rosetta Code Tic-Tac-Toe for C#.\");\n        initializeGameBoard();\n        displayGameBoard();\n        int currentPlayer = rnd.Next(0, 2);  \n        Console.WriteLine(\"The first move goes to {0} who is playing {1}s.\\n\", playerName(currentPlayer), playerToken(currentPlayer));\n        while (true)\n        {\n          int thisMove = getMoveFor(currentPlayer);\n          if (thisMove == Unplayed)\n          {\n            Console.WriteLine(\"{0}, you've quit the game ... am I that good?\", playerName(currentPlayer));\n            break;\n          }\n          playMove(thisMove, currentPlayer);\n          displayGameBoard();\n          if (isGameWon())\n          {\n            Console.WriteLine(\"{0} has won the game!\", playerName(currentPlayer));\n            break;\n          }\n          else if (isGameTied())\n          {\n            Console.WriteLine(\"Cat game ... we have a tie.\");\n            break;\n          }\n          currentPlayer = getNextPlayer(currentPlayer);\n        }\n        if (!playAgain())\n          return;\n      }\n    }\n\n    \n    static int getMoveFor(int player)\n    {\n      if (player == Human)\n        return getManualMove(player);\n      else\n      {\n        \n        \n        int selectedMove = getSemiRandomMove(player);\n        \n        Console.WriteLine(\"{0} selects position {1}.\", playerName(player), selectedMove + 1);\n        return selectedMove;\n      }\n    }\n\n    static int getManualMove(int player)\n    {\n      while (true)\n      {\n        Console.Write(\"{0}, enter you move (number): \", playerName(player));\n        ConsoleKeyInfo keyInfo = Console.ReadKey();\n        Console.WriteLine();  \n        if (keyInfo.Key == ConsoleKey.Escape)\n          return Unplayed;\n        if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)\n        {\n          int move = keyInfo.KeyChar - '1';  \n          if (GameBoard[move] == Unplayed)\n            return move;\n          else\n            Console.WriteLine(\"Spot {0} is already taken, please select again.\", move + 1);\n        }\n        else\n          Console.WriteLine(\"Illegal move, please select again.\\n\");\n      }\n    }\n\n    static int getRandomMove(int player)\n    {\n      int movesLeft = GameBoard.Count(position => position == Unplayed);\n      int x = rnd.Next(0, movesLeft);\n      for (int i = 0; i < GameBoard.Length; i++)  \n      {\n        if (GameBoard[i] == Unplayed && x < 0)    \n          return i;\n        x--;\n      }\n      return Unplayed;\n    }\n\n    \n    static int getSemiRandomMove(int player)\n    {\n      int posToPlay;\n      if (checkForWinningMove(player, out posToPlay))\n        return posToPlay;\n      if (checkForBlockingMove(player, out posToPlay))\n        return posToPlay;\n      return getRandomMove(player);\n    }\n\n    \n    static int getBestMove(int player)\n    {\n      return -1;\n    }\n\n    static bool checkForWinningMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(player, line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool checkForBlockingMove(int player, out int posToPlay)\n    {\n      posToPlay = Unplayed;\n      foreach (var line in wins)\n        if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))\n          return true;\n      return false;\n    }\n\n    static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)\n    {\n      int cnt = 0;\n      posToPlay = int.MinValue;\n      foreach (int pos in line)\n      {\n        if (GameBoard[pos] == player)\n          cnt++;\n        else if (GameBoard[pos] == Unplayed)\n          posToPlay = pos;\n      }\n      return cnt == 2 && posToPlay >= 0;\n    }\n\n    static void playMove(int boardPosition, int player)\n    {\n      GameBoard[boardPosition] = player;\n    }\n\n    static bool isGameWon()\n    {\n      return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));\n    }\n\n    static bool takenBySamePlayer(int a, int b, int c)\n    {\n      return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];\n    }\n\n    static bool isGameTied()\n    {\n      return !GameBoard.Any(spot => spot == Unplayed);\n    }\n\n    \n    static Random rnd = new Random();\n\n    static void initializeGameBoard()\n    {\n      for (int i = 0; i < GameBoard.Length; i++)\n        GameBoard[i] = Unplayed;\n    }\n\n    static string playerName(int player)\n    {\n      return Players[player][0];\n    }\n\n    static string playerToken(int player)\n    {\n      return Players[player][1];\n    }\n\n    static int getNextPlayer(int player)\n    {\n      return (player + 1) % 2;\n    }\n\n    static void displayGameBoard()\n    {\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(0), pieceAt(1), pieceAt(2));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(3), pieceAt(4), pieceAt(5));\n      Console.WriteLine(\"---|---|---\");\n      Console.WriteLine(\" {0} | {1} | {2}\", pieceAt(6), pieceAt(7), pieceAt(8));\n      Console.WriteLine();\n    }\n\n    static string pieceAt(int boardPosition)\n    {\n      if (GameBoard[boardPosition] == Unplayed)\n        return (boardPosition + 1).ToString();  \n      return playerToken(GameBoard[boardPosition]);\n    }\n\n    private static bool playAgain()\n    {\n      Console.WriteLine(\"\\nDo you want to play again?\");\n      return Console.ReadKey(false).Key == ConsoleKey.Y;\n    }\n  }\n\n}\n"}
{"id": 45411, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n"}
{"id": 45412, "name": "Integer sequence", "Python": "i=1\nwhile i:\n    print(i)\n    i += 1\n", "C#": "using System;\nusing System.Numerics;\n\nclass Program\n{\n    static void Main()\n    {\n        BigInteger i = 1;\n        while (true)\n        {\n            Console.WriteLine(i++);\n        }\n    }\n}\n"}
{"id": 45413, "name": "DNS query", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n"}
{"id": 45414, "name": "DNS query", "Python": ">>> import socket\n>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))\n>>> for ip in ips: print ip\n...\n2001:200:dff:fff1:216:3eff:feb1:44d7\n203.178.141.194\n", "C#": "        private string LookupDns(string s)\n        {\n            try\n            {\n                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);\n\n                string result = ip.AddressList[0].ToString();\n\n                for (int i = 1; i < ip.AddressList.Length; ++i)\n                    result += \", \" + ip.AddressList[i].ToString();\n\n                return result;\n            }\n            catch (System.Net.Sockets.SocketException se)\n            {\n                return se.Message;\n            }\n        }\n"}
{"id": 45415, "name": "Seven-sided dice from five-sided dice", "Python": "from random import randint\n\ndef dice5():\n    return randint(1, 5)\n\ndef dice7():\n    r = dice5() + dice5() * 5 - 6\n    return (r % 7) + 1 if r < 21 else dice7()\n", "C#": "using System;\n\npublic class SevenSidedDice\n{\n    Random random = new Random();\n\t\t\n        static void Main(string[] args)\n\t\t{\n\t\t\tSevenSidedDice sevenDice = new SevenSidedDice();\n\t\t\tConsole.WriteLine(\"Random number from 1 to 7: \"+ sevenDice.seven());\n            Console.Read();\n\t\t}\n\t\t\n\t\tint seven()\n\t\t{\n\t\t\tint v=21;\n\t\t\twhile(v>20)\n\t\t\t\tv=five()+five()*5-6;\n\t\t\treturn 1+v%7;\n\t\t}\n\t\t\n\t\tint five()\n\t\t{\n        return 1 + random.Next(5);\n\t\t}\n}\n"}
{"id": 45416, "name": "Create a two-dimensional array at runtime", "Python": "width = int(raw_input(\"Width of myarray: \"))\nheight = int(raw_input(\"Height of Array: \"))\nmyarray = [[0] * width for i in range(height)]\nmyarray[0][0] = 3.5\nprint (myarray[0][0])\n", "C#": "class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(\"Enter two integers. Space delimited please: \");\n            string s = Console.ReadLine();\n            \n            int[,] myArray=new int[(int)s[0],(int)s[2]];\n            myArray[0, 0] = 2;\n            Console.WriteLine(myArray[0, 0]);\n\n            Console.ReadLine();\n        }\n    }\n"}
{"id": 45417, "name": "Chinese remainder theorem", "Python": "\ndef chinese_remainder(n, a):\n    sum = 0\n    prod = reduce(lambda a, b: a*b, n)\n\n    for n_i, a_i in zip(n, a):\n        p = prod / n_i\n        sum += a_i * mul_inv(p, n_i) * p\n    return sum % prod\n\n\ndef mul_inv(a, b):\n    b0 = b\n    x0, x1 = 0, 1\n    if b == 1: return 1\n    while a > 1:\n        q = a / b\n        a, b = b, a%b\n        x0, x1 = x1 - q * x0, x0\n    if x1 < 0: x1 += b0\n    return x1\n\nif __name__ == '__main__':\n    n = [3, 5, 7]\n    a = [2, 3, 2]\n    print chinese_remainder(n, a)\n", "C#": "using System;\nusing System.Linq;\n\nnamespace ChineseRemainderTheorem\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] n = { 3, 5, 7 };\n            int[] a = { 2, 3, 2 };\n\n            int result = ChineseRemainderTheorem.Solve(n, a);\n\n            int counter = 0;\n            int maxCount = n.Length - 1;\n            while (counter <= maxCount)\n            {\n                Console.WriteLine($\"{result} ≡ {a[counter]} (mod {n[counter]})\");\n                counter++;\n            }\n        }\n    }\n\n    public static class ChineseRemainderTheorem\n    {\n        public static int Solve(int[] n, int[] a)\n        {\n            int prod = n.Aggregate(1, (i, j) => i * j);\n            int p;\n            int sm = 0;\n            for (int i = 0; i < n.Length; i++)\n            {\n                p = prod / n[i];\n                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;\n            }\n            return sm % prod;\n        }\n\n        private static int ModularMultiplicativeInverse(int a, int mod)\n        {\n            int b = a % mod;\n            for (int x = 1; x < mod; x++)\n            {\n                if ((b * x) % mod == 1)\n                {\n                    return x;\n                }\n            }\n            return 1;\n        }\n    }\n}\n"}
{"id": 45418, "name": "Bitwise operations", "VB": "Debug.Print Hex(&HF0F0 And &HFF00)  \nDebug.Print Hex(&HF0F0 Or &HFF00)   \nDebug.Print Hex(&HF0F0 Xor &HFF00)  \nDebug.Print Hex(Not &HF0F0)         \nDebug.Print Hex(&HF0F0 Eqv &HFF00)  \nDebug.Print Hex(&HF0F0 Imp &HFF00)  \n", "Java": "module BitwiseOps\n    {\n    @Inject Console console;\n    void run()\n        {\n        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  \n            {\n            static String hex(Int64 n)   \n                {\n                \n                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();\n                }\n\n            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):\n                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}\n                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}\n                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}\n                           |  NOT {hex(n1)} = {hex(~n1)}\n                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}\n                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}\n                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}\n                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}\n                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}\n                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}\n                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}\n                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}\n                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}\n                           |  bit count (aka \"population\") of {hex(n1)} = {n1.bitCount}\n                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}\n                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}\n                           |\n                         );\n            }\n        }\n    }\n"}
{"id": 45419, "name": "Dragon curve", "VB": "option explicit\n\n\nconst pi180= 0.01745329251994329576923690768489 \nconst pi=3.1415926535897932384626433832795 \nclass turtle\n   \n   dim fso\n   dim fn\n   dim svg\n   \n   dim iang  \n   dim ori   \n   dim incr\n   dim pdown\n   dim clr\n   dim x\n   dim y\n\n   public property let orient(n):ori = n*pi180 :end property\n   public property let iangle(n):iang= n*pi180 :end property\n   public sub pd() : pdown=true: end sub \n   public sub pu()  :pdown=FALSE :end sub \n   \n   public sub rt(i)  \n     ori=ori - i*iang:\n     \n   end sub \n   public sub lt(i):  \n     ori=(ori + i*iang) \n     \n   end sub\n   \n   public sub bw(l)\n      x= x+ cos(ori+pi)*l*incr\n      y= y+ sin(ori+pi)*l*incr\n     \n   end sub \n   \n   public sub fw(l)\n      dim x1,y1 \n      x1=x + cos(ori)*l*incr\n      y1=y + sin(ori)*l*incr\n      if pdown then line x,y,x1,y1\n      x=x1:y=y1\n   end sub\n   \n   Private Sub Class_Initialize()  \n      setlocale \"us\"   \n      initsvg\n      x=400:y=400:incr=100\n      ori=90*pi180\n      iang=90*pi180\n      clr=0\n      pdown=true\n   end sub\n   \n   Private Sub Class_Terminate()   \n      disply\n   end sub\n   \n   private sub line (x,y,x1,y1)\n      svg.WriteLine \"<line x1=\"\"\" & x & \"\"\" y1= \"\"\"& y & \"\"\" x2=\"\"\" & x1& \"\"\" y2=\"\"\" & y1 & \"\"\"/>\"\n   end sub \n\n   private sub disply()\n       dim shell\n       svg.WriteLine \"</svg></body></html>\"\n       svg.close\n       Set shell = CreateObject(\"Shell.Application\") \n       shell.ShellExecute fn,1,False\n   end sub \n\n   private sub initsvg()\n     dim scriptpath\n     Set fso = CreateObject (\"Scripting.Filesystemobject\")\n     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, \"\\\"))\n     fn=Scriptpath & \"SIERP.HTML\"\n     Set svg = fso.CreateTextFile(fn,True)\n     if SVG IS nothing then wscript.echo \"Can\n     svg.WriteLine \"<!DOCTYPE html>\" &vbcrlf & \"<html>\" &vbcrlf & \"<head>\"\n     svg.writeline \"<style>\" & vbcrlf & \"line {stroke:rgb(255,0,0);stroke-width:.5}\" &vbcrlf &\"</style>\"\n     svg.writeline \"</head>\"&vbcrlf & \"<body>\"\n     svg.WriteLine \"<svg xmlns=\"\"http://www.w3.org/2000/svg\"\" width=\"\"800\"\" height=\"\"800\"\" viewBox=\"\"0 0 800 800\"\">\" \n   end sub \nend class\n\nsub dragon(st,le,dir)\nif st=0 then x.fw le: exit sub\n  x.rt dir\n  dragon st-1, le/1.41421 ,1\n  x.rt dir*2\n  dragon st-1, le/1.41421 ,-1\n  x.rt dir\nend sub\n\n \ndim x\nset x=new turtle\nx.iangle=45\nx.orient=45\nx.incr=1\nx.x=200:x.y=200\ndragon 12,300,1\nset x=nothing   \n", "Java": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n    private List<Integer> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter) {\n        super(\"Dragon Curve\");\n        setBounds(100, 100, 800, 600);\n        setDefaultCloseOperation(EXIT_ON_CLOSE);\n        turns = getSequence(iter);\n        startingAngle = -iter * (Math.PI / 4);\n        side = 400 / Math.pow(2, iter / 2.);\n    }\n\n    public List<Integer> getSequence(int iterations) {\n        List<Integer> turnSequence = new ArrayList<Integer>();\n        for (int i = 0; i < iterations; i++) {\n            List<Integer> copy = new ArrayList<Integer>(turnSequence);\n            Collections.reverse(copy);\n            turnSequence.add(1);\n            for (Integer turn : copy) {\n                turnSequence.add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.BLACK);\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int) (Math.cos(angle) * side);\n        int y2 = y1 + (int) (Math.sin(angle) * side);\n        g.drawLine(x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        for (Integer turn : turns) {\n            angle += turn * (Math.PI / 2);\n            x2 = x1 + (int) (Math.cos(angle) * side);\n            y2 = y1 + (int) (Math.sin(angle) * side);\n            g.drawLine(x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    public static void main(String[] args) {\n        new DragonCurve(14).setVisible(true);\n    }\n}\n"}
{"id": 45420, "name": "Read a file line by line", "VB": "$Include \"Rapidq.inc\"\ndim file as qfilestream\n\nif file.open(\"c:\\A Test.txt\", fmOpenRead) then\n    while not File.eof\n        print File.readline\n    wend\nelse\n    print \"Cannot read file\"\nend if\n\ninput \"Press enter to exit: \";a$\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\n\npublic class ReadFileByLines {\n    private static void processLine(int lineNo, String line) {\n        \n    }\n\n    public static void main(String[] args) {\n        for (String filename : args) {\n            BufferedReader br = null;\n            FileReader fr = null;\n            try {\n                fr = new FileReader(filename);\n                br = new BufferedReader(fr);\n                String line;\n                int lineNo = 0;\n                while ((line = br.readLine()) != null) {\n                    processLine(++lineNo, line);\n                }\n            }\n            catch (Exception x) {\n                x.printStackTrace();\n            }\n            finally {\n                if (fr != null) {\n                    try {br.close();} catch (Exception ignoreMe) {}\n                    try {fr.close();} catch (Exception ignoreMe) {}\n                }\n            }\n        }\n    }\n}\n"}
{"id": 45421, "name": "Doubly-linked list_Element insertion", "VB": "Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)\n    Dim node As New Node(Of T)(value)\n    a.Next = node\n    node.Previous = a\n    b.Previous = node\n    node.Next = b\nEnd Sub\n", "Java": "import java.util.LinkedList;\n\n@SuppressWarnings(\"serial\")\npublic class DoublyLinkedListInsertion<T> extends LinkedList<T> {\n   \n    public static void main(String[] args) {\n        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();\n        list.addFirst(\"Add First 1\");\n        list.addFirst(\"Add First 2\");\n        list.addFirst(\"Add First 3\");\n        list.addFirst(\"Add First 4\");\n        list.addFirst(\"Add First 5\");\n        traverseList(list);\n        \n        list.addAfter(\"Add First 3\", \"Add New\");\n        traverseList(list);\n    }\n    \n    \n    public void addAfter(T after, T element) {\n        int index = indexOf(after);\n        if ( index >= 0 ) {\n            add(index + 1, element);\n        }\n        else {\n            addLast(element);\n        }\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 45422, "name": "Quickselect algorithm", "VB": "Dim s As Variant\nPrivate Function quick_select(ByRef s As Variant, k As Integer) As Integer\n    Dim left As Integer, right As Integer, pos As Integer\n    Dim pivotValue As Integer, tmp As Integer\n    left = 1: right = UBound(s)\n    Do While left < right\n        pivotValue = s(k)\n        tmp = s(k)\n        s(k) = s(right)\n        s(right) = tmp\n        pos = left\n        For i = left To right\n            If s(i) < pivotValue Then\n                tmp = s(i)\n                s(i) = s(pos)\n                s(pos) = tmp\n                pos = pos + 1\n            End If\n        Next i\n        tmp = s(right)\n        s(right) = s(pos)\n        s(pos) = tmp\n        If pos = k Then\n            Exit Do\n        End If\n        If pos < k Then\n            left = pos + 1\n        Else\n            right = pos - 1\n        End If\n    Loop\n    quick_select = s(k)\nEnd Function\nPublic Sub main()\n    Dim r As Integer, i As Integer\n    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]\n    For i = 1 To 10\n        r = quick_select(s, i) \n        Debug.Print IIf(i < 10, r & \", \", \"\" & r);\n    Next i\nEnd Sub\n", "Java": "import java.util.Random;\n\npublic class QuickSelect {\n\n\tprivate static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {\n\t\tE pivotVal = arr[pivot];\n\t\tswap(arr, pivot, right);\n\t\tint storeIndex = left;\n\t\tfor (int i = left; i < right; i++) {\n\t\t\tif (arr[i].compareTo(pivotVal) < 0) {\n\t\t\t\tswap(arr, i, storeIndex);\n\t\t\t\tstoreIndex++;\n\t\t\t}\n\t\t}\n\t\tswap(arr, right, storeIndex);\n\t\treturn storeIndex;\n\t}\n\t\n\tprivate static <E extends Comparable<? super E>> E select(E[] arr, int n) {\n\t\tint left = 0;\n\t\tint right = arr.length - 1;\n\t\tRandom rand = new Random();\n\t\twhile (right >= left) {\n\t\t\tint pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);\n\t\t\tif (pivotIndex == n) {\n\t\t\t\treturn arr[pivotIndex];\n\t\t\t} else if (pivotIndex < n) {\n\t\t\t\tleft = pivotIndex + 1;\n\t\t\t} else {\n\t\t\t\tright = pivotIndex - 1;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate static void swap(Object[] arr, int i1, int i2) {\n\t\tif (i1 != i2) {\n\t\t\tObject temp = arr[i1];\n\t\t\tarr[i1] = arr[i2];\n\t\t\tarr[i2] = temp;\n\t\t}\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tInteger[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\t\t\tSystem.out.print(select(input, i));\n\t\t\tif (i < 9) System.out.print(\", \");\n\t\t}\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 45423, "name": "Non-decimal radices_Convert", "VB": "Private Function to_base(ByVal number As Long, base As Integer) As String\n    Dim digits As String, result As String\n    Dim i As Integer, digit As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    Do While number > 0\n        digit = number Mod base\n        result = Mid(digits, digit + 1, 1) & result\n        number = number \\ base\n    Loop\n    to_base = result\nEnd Function\nPrivate Function from_base(number As String, base As Integer) As Long\n    Dim digits As String, result As Long\n    Dim i As Integer\n    digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)\n    For i = 2 To Len(number)\n        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)\n    Next i\n    from_base = result\nEnd Function\nPublic Sub Non_decimal_radices_Convert()\n    Debug.Print \"26 decimal in base 16 is: \"; to_base(26, 16); \". Conversely, hexadecimal 1a in decimal is: \"; from_base(\"1a\", 16)\nEnd Sub\n", "Java": "public static long backToTen(String num, int oldBase){\n   return Long.parseLong(num, oldBase); \n}\n\npublic static String tenToBase(long num, int newBase){\n   return Long.toString(num, newBase);\n}\n"}
{"id": 45424, "name": "Walk a directory_Recursively", "VB": "Sub printFiles(parentDir As FolderItem, pattern As String)\n  For i As Integer = 1 To parentDir.Count\n    If parentDir.Item(i).Directory Then\n      printFiles(parentDir.Item(i), pattern)\n    Else\n      Dim rg as New RegEx\n      Dim myMatch as RegExMatch\n      rg.SearchPattern = pattern\n      myMatch = rg.search(parentDir.Item(i).Name)\n      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)\n    End If\n  Next\nEnd Sub\n", "Java": "import java.io.File;\n\npublic class MainEntry {\n    public static void main(String[] args) {\n        walkin(new File(\"/home/user\")); \n    }\n    \n    \n    public static void walkin(File dir) {\n        String pattern = \".mp3\";\n        \n        File listFile[] = dir.listFiles();\n        if (listFile != null) {\n            for (int i=0; i<listFile.length; i++) {\n                if (listFile[i].isDirectory()) {\n                    walkin(listFile[i]);\n                } else {\n                    if (listFile[i].getName().endsWith(pattern)) {\n                        System.out.println(listFile[i].getPath());\n                    }\n                }\n            }\n        }\n    }\n}\n"}
{"id": 45425, "name": "CRC-32", "VB": "dim crctbl(255)\nconst crcc =&hEDB88320\n\nsub gencrctable\nfor i= 0 to 255\n   k=i\n   for j=1 to 8\n    if k and 1 then \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0)) \n      k=k xor crcc\n    else \n      k=(k and &h7fffffff)\\2 or (&h40000000 and ((k and &h80000000)<>0))\n   end if\n   next \n   crctbl(i)=k\n next\nend sub\n \n function crc32 (buf) \n  dim r,r1,i \n  r=&hffffffff \n  for i=1 to len(buf) \n      r1=(r and &h7fffffff)\\&h100 or (&h800000 and (r and &h80000000)<>0)\n    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) \n  next \n  crc32=r xor &hffffffff\nend function\n\n  \n\ngencrctable\nwscript.stdout.writeline hex(crc32(\"The quick brown fox jumps over the lazy dog\"))\n", "Java": "import java.util.zip.* ;\n\npublic class CRCMaker {\n   public static void main( String[ ] args ) {\n      String toBeEncoded = new String( \"The quick brown fox jumps over the lazy dog\" ) ;\n      CRC32 myCRC = new CRC32( ) ;\n      myCRC.update( toBeEncoded.getBytes( ) ) ;\n      System.out.println( \"The CRC-32 value is : \" + Long.toHexString( myCRC.getValue( ) ) + \" !\" ) ;\n   }\n}\n"}
{"id": 45426, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 45427, "name": "CSV to HTML translation", "VB": "Public Sub CSV_TO_HTML()\n    input_ = \"Character,Speech\\n\" & _\n        \"The multitude,The messiah! Show us the messiah!\\n\" & _\n        \"Brians mother,<angry>Now you listen here! He\n            \"he\n        \"The multitude,Who are you?\\n\" & _\n        \"Brians mother,I\n        \"The multitude,Behold his mother! Behold his mother!\"\n     \n    Debug.Print \"<table>\" & vbCrLf & \"<tr><td>\"\n    For i = 1 To Len(input_)\n        Select Case Mid(input_, i, 1)\n            Case \"\\\"\n                If Mid(input_, i + 1, 1) = \"n\" Then\n                    Debug.Print \"</td></tr>\" & vbCrLf & \"<tr><td>\";\n                    i = i + 1\n                Else\n                    Debug.Print Mid(input_, i, 1);\n                End If\n            Case \",\": Debug.Print \"</td><td>\";\n            Case \"<\": Debug.Print \"&lt;\";\n            Case \">\": Debug.Print \"&gt;\";\n            Case \"&\": Debug.Print \"&amp;\";\n            Case Else: Debug.Print Mid(input_, i, 1);\n        End Select\n    Next i\n    Debug.Print \"</td></tr>\" & vbCrLf & \"</table>\"\nEnd Sub\n", "Java": "\n\ngrammar csv2html;\ndialog : {System.out.println(\"<HTML><Table>\");}header body+{System.out.println(\"</Table></HTML>\");} ;\nheader : {System.out.println(\"<THEAD align=\\\"center\\\"><TR bgcolor=\\\"blue\\\">\");}row{System.out.println(\"</TR></THEAD\");};\nbody   : {System.out.println(\"<TBODY><TR>\");}row{System.out.println(\"</TR></TBODY\");};\nrow    : field ',' field '\\r'? '\\n';\nfield  : Field{System.out.println(\"<TD>\" + $Field.text.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\") + \"</TD>\");};\nField  : ~[,\\n\\r]+;\n"}
{"id": 45428, "name": "Classes", "VB": "Class NumberContainer\n  Private TheNumber As Integer\n  Sub Constructor(InitialNumber As Integer)\n    TheNumber = InitialNumber\n  End Sub\n\n  Function Number() As Integer\n    Return TheNumber\n  End Function\n\n  Sub Number(Assigns NewNumber As Integer)\n    TheNumber = NewNumber\n  End Sub\nEnd Class\n", "Java": "public class MyClass{\n\n  \n  private int variable;  \n\n  \n  public MyClass(){\n    \n  }\n\n  \n  public void someMethod(){\n   this.variable = 1;\n  }\n}\n"}
{"id": 45429, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 45430, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 45431, "name": "Kaprekar numbers", "VB": "Module Module1\n\n    ReadOnly max As ULong = 1000000\n\n    Function Kaprekar(n As ULong) As Boolean\n        If n = 1 Then Return True\n\n        Dim sq = n * n\n        Dim sq_str = Str(sq)\n        Dim l = Len(sq_str)\n\n        For x = l - 1 To 1 Step -1\n            If sq_str(x) = \"0\" Then\n                l = l - 1\n            Else\n                Exit For\n            End If\n        Next\n\n        For x = 1 To l - 1\n            Dim p2 = Val(Mid(sq_str, x + 1))\n            If p2 > n Then\n                Continue For\n            End If\n            Dim p1 = Val(Left(sq_str, x))\n            If p1 > n Then Return False\n            If (p1 + p2) = n Then Return True\n        Next\n\n        Return False\n    End Function\n\n    Sub Main()\n        Dim count = 0\n\n        Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n        For n = 1 To max - 1\n            If Kaprekar(n) Then\n                count = count + 1\n                If n < 10000 Then\n                    Console.WriteLine(\"{0,2} {1,4}\", count, n)\n                End If\n            End If\n        Next\n\n        Console.WriteLine()\n        Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n    End Sub\n\nEnd Module\n", "Java": "public class Kaprekar {\n    private static String[] splitAt(String str, int idx){\n        String[] ans = new String[2];\n        ans[0] = str.substring(0, idx);\n        if(ans[0].equals(\"\")) ans[0] = \"0\"; \n        ans[1] = str.substring(idx);\n        return ans;\n    }\n        \n    public static void main(String[] args){\n        int count = 0;\n        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;\n        for(long i = 1; i <= 1000000; i++){\n            String sqrStr = Long.toString(i * i, base);\n            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){\n                String[] parts = splitAt(sqrStr, j);\n                long firstNum = Long.parseLong(parts[0], base);\n                long secNum = Long.parseLong(parts[1], base);\n                \n                if(secNum == 0) break;\n                if(firstNum + secNum == i){\n                    System.out.println(i + \"\\t\" + Long.toString(i, base) +\n                            \"\\t\" + sqrStr + \"\\t\" + parts[0] + \" + \" + parts[1]);\n                    count++;\n                    break;\n                }\n            }\n        }\n        System.out.println(count + \" Kaprekar numbers < 1000000 (base 10) in base \"+base);\n    }\n}\n"}
{"id": 45432, "name": "LZW compression", "VB": "Option Explicit\nConst numchars=127  \n\nFunction LZWCompress(si)\n  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j\n  Set oDict = CreateObject(\"Scripting.Dictionary\")\n  ReDim a(Len(si))\n  \n  intMaxCode = numchars\n  For i = 0 To numchars\n    oDict.Add Chr(i), i\n  Next\n  \n  strCurrent = Left(si,1)\n  j=0\n  For ii=2 To Len(si)\n    strNext = Mid(si,ii,1)\n    ss=strCurrent & strNext\n    If oDict.Exists(ss) Then\n      strCurrent = ss\n    Else\n      a(j)=oDict.Item(strCurrent) :j=j+1\n      intMaxCode = intMaxCode + 1\n      oDict.Add ss, intMaxCode\n      strCurrent = strNext\n    End If\n  Next\n  a(j)=oDict.Item(strCurrent) \n  ReDim preserve a(j)\n  LZWCompress=a\n  Set oDict = Nothing\nEnd Function\n\nFunction lzwUncompress(sc)\n  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j\n  s=\"\"     \n  reDim dict(1000)\n  intMaxCode = numchars\n  For i = 0 To numchars : dict(i)= Chr(i) :  Next\n    intCurrent=sc(0)\n    \n    For j=1 To UBound(sc)\n      ss=dict(intCurrent)\n      s= s & ss\n      intMaxCode = intMaxCode + 1\n      intnext=sc(j)\n      If intNext<intMaxCode Then\n        dict(intMaxCode)=ss & Left(dict(intNext), 1)\n      Else\n        dict(intMaxCode)=ss & Left(ss, 1) \n      End If\n      intCurrent = intNext\n    Next\n    s= s & dict(intCurrent)\n    lzwUncompress=s\nEnd function\n\nSub printvec(a)\n  Dim s,i,x\n  s=\"(\"\n  For i=0 To UBound (a)\n   s=s & x & a(i)\n   x=\", \"\n  Next \n  WScript.echo s &\")\"\nEnd sub\n\nDim a,b\nb=\"TOBEORNOTTOBEORTOBEORNOT\"\nWScript.Echo b\na=LZWCompress (b)\nprintvec(a)\nWScript.echo lzwUncompress (a )\nwscript.quit 1\n", "Java": "import java.util.*;\n\npublic class LZW {\n    \n    public static List<Integer> compress(String uncompressed) {\n        \n        int dictSize = 256;\n        Map<String,Integer> dictionary = new HashMap<String,Integer>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(\"\" + (char)i, i);\n        \n        String w = \"\";\n        List<Integer> result = new ArrayList<Integer>();\n        for (char c : uncompressed.toCharArray()) {\n            String wc = w + c;\n            if (dictionary.containsKey(wc))\n                w = wc;\n            else {\n                result.add(dictionary.get(w));\n                \n                dictionary.put(wc, dictSize++);\n                w = \"\" + c;\n            }\n        }\n \n        \n        if (!w.equals(\"\"))\n            result.add(dictionary.get(w));\n        return result;\n    }\n    \n    \n    public static String decompress(List<Integer> compressed) {\n        \n        int dictSize = 256;\n        Map<Integer,String> dictionary = new HashMap<Integer,String>();\n        for (int i = 0; i < 256; i++)\n            dictionary.put(i, \"\" + (char)i);\n        \n        String w = \"\" + (char)(int)compressed.remove(0);\n        StringBuffer result = new StringBuffer(w);\n        for (int k : compressed) {\n            String entry;\n            if (dictionary.containsKey(k))\n                entry = dictionary.get(k);\n            else if (k == dictSize)\n                entry = w + w.charAt(0);\n            else\n                throw new IllegalArgumentException(\"Bad compressed k: \" + k);\n            \n            result.append(entry);\n            \n            \n            dictionary.put(dictSize++, w + entry.charAt(0));\n            \n            w = entry;\n        }\n        return result.toString();\n    }\n\n    public static void main(String[] args) {\n        List<Integer> compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\");\n        System.out.println(compressed);\n        String decompressed = decompress(compressed);\n        System.out.println(decompressed);\n    }\n}\n"}
{"id": 45433, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 45434, "name": "Hofstadter Figure-Figure sequences", "VB": "Private Function ffr(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n    Next i\n    ffr = R(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPrivate Function ffs(n As Long) As Long\n    Dim R As New Collection\n    Dim S As New Collection\n    R.Add 1\n    S.Add 2\n    \n    For i = 2 To n\n        R.Add R(i - 1) + S(i - 1)\n        For j = S(S.Count) + 1 To R(i) - 1\n            S.Add j\n        Next j\n        For j = R(i) + 1 To R(i) + S(i - 1)\n            S.Add j\n        Next j\n        If S.Count >= n Then Exit For\n    Next i\n    ffs = S(n)\n    Set R = Nothing\n    Set S = Nothing\nEnd Function\nPublic Sub main()\n    Dim i As Long\n    Debug.Print \"The first ten values of R are:\"\n    For i = 1 To 10\n        Debug.Print ffr(i);\n    Next i\n    Debug.Print\n    Dim x As New Collection\n    For i = 1 To 1000\n        x.Add i, CStr(i)\n    Next i\n    For i = 1 To 40\n        x.Remove CStr(ffr(i))\n    Next i\n    For i = 1 To 960\n        x.Remove CStr(ffs(i))\n    Next i\n    Debug.Print \"The first 40 values of ffr plus the first 960 values of ffs \"\n    Debug.Print \"include all the integers from 1 to 1000 exactly once is \"; Format(x.Count = 0)\nEnd Sub\n", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n  private static List<Integer> getSequence(int rlistSize, int slistSize)\n  {\n    List<Integer> rlist = new ArrayList<Integer>();\n    List<Integer> slist = new ArrayList<Integer>();\n    Collections.addAll(rlist, 1, 3, 7);\n    Collections.addAll(slist, 2, 4, 5, 6);\n    List<Integer> list = (rlistSize > 0) ? rlist : slist;\n    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n    while (list.size() > targetSize)\n      list.remove(list.size() - 1);\n    while (list.size() < targetSize)\n    {\n      int lastIndex = rlist.size() - 1;\n      int lastr = rlist.get(lastIndex).intValue();\n      int r = lastr + slist.get(lastIndex).intValue();\n      rlist.add(Integer.valueOf(r));\n      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n        slist.add(Integer.valueOf(s));\n    }\n    return list;\n  }\n  \n  public static int ffr(int n)\n  {  return getSequence(n, 0).get(n - 1).intValue();  }\n  \n  public static int ffs(int n)\n  {  return getSequence(0, n).get(n - 1).intValue();  }\n  \n  public static void main(String[] args)\n  {\n    System.out.print(\"R():\");\n    for (int n = 1; n <= 10; n++)\n      System.out.print(\" \" + ffr(n));\n    System.out.println();\n    \n    Set<Integer> first40R = new HashSet<Integer>();\n    for (int n = 1; n <= 40; n++)\n      first40R.add(Integer.valueOf(ffr(n)));\n      \n    Set<Integer> first960S = new HashSet<Integer>();\n    for (int n = 1; n <= 960; n++)\n      first960S.add(Integer.valueOf(ffs(n)));\n    \n    for (int i = 1; i <= 1000; i++)\n    {\n      Integer n = Integer.valueOf(i);\n      if (first40R.contains(n) == first960S.contains(n))\n        System.out.println(\"Integer \" + i + \" either in both or neither set\");\n    }\n    System.out.println(\"Done\");\n  }\n}\n"}
{"id": 45435, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 45436, "name": "Magic squares of odd order", "VB": "Sub magicsquare()\n    \n    Const n = 9\n    Dim i As Integer, j As Integer, v As Integer\n    Debug.Print \"The square order is: \" & n\n    For i = 1 To n\n        For j = 1 To n\n            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1\n        Next j\n    Next i\n    Debug.Print \"The magic number of\"; n; \"x\"; n; \"square is:\"; n * (n * n + 1) \\ 2\nEnd Sub \n", "Java": "public class MagicSquare {\n\n    public static void main(String[] args) {\n        int n = 5;\n        for (int[] row : magicSquareOdd(n)) {\n            for (int x : row)\n                System.out.format(\"%2s \", x);\n            System.out.println();\n        }\n        System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n    }\n\n    public static int[][] magicSquareOdd(final int base) {\n        if (base % 2 == 0 || base < 3)\n            throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n        int[][] grid = new int[base][base];\n        int r = 0, number = 0;\n        int size = base * base;\n\n        int c = base / 2;\n        while (number++ < size) {\n            grid[r][c] = number;\n            if (r == 0) {\n                if (c == base - 1) {\n                    r++;\n                } else {\n                    r = base - 1;\n                    c++;\n                }\n            } else {\n                if (c == base - 1) {\n                    r--;\n                    c = 0;\n                } else {\n                    if (grid[r - 1][c + 1] == 0) {\n                        r--;\n                        c++;\n                    } else {\n                        r++;\n                    }\n                }\n            }\n        }\n        return grid;\n    }\n}\n"}
{"id": 45437, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 45438, "name": "Benford's law", "VB": "Sub BenfordLaw()\n\nDim BenResult(1 To 9) As Long\n\nBENref = \"30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%\"\n\nFor Each c In Selection.Cells\n  If InStr(1, \"-0123456789\", Left(c, 1)) > 0 Then\n    For i = 1 To 9\n      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For\n    Next\n  End If\nNext\nTotal= Application.Sum(BenResult)\nbiggest= Len(CStr(BenResult(1)))\n\ntxt = \"#   |   Values    |     Real     |  Expected   \" & vbCrLf\nFor i = 1 To 9\n  If BenResult(i) > 0 Then\n    txt = txt & \"#\" & i & \" | \" & vbTab\n    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, \" \") & Format(BenResult(i), \"0\") & \" | \" & vbTab\n    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, \"##0.0%\"))) - Len(CStr(Format(BenResult(i) / Total, \"##0.0%\")))) * 2, \" \") & Format(BenResult(i) / Total, \"##0.0%\") & \" | \" & vbTab\n    txt = txt & Format(Split(BENref, \"|\")(i - 1), \"     ##0.0%\") & vbCrLf\n  End If\nNext\n\nMsgBox txt, vbOKOnly, \"Finish\"\n\nEnd Sub\n\n}\n", "Java": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n    private static BigInteger[] generateFibonacci(int n) {\n        BigInteger[] fib = new BigInteger[n];\n        fib[0] = BigInteger.ONE;\n        fib[1] = BigInteger.ONE;\n        for (int i = 2; i < fib.length; i++) {\n            fib[i] = fib[i - 2].add(fib[i - 1]);\n        }\n        return fib;\n    }\n\n    public static void main(String[] args) {\n        BigInteger[] numbers = generateFibonacci(1000);\n\n        int[] firstDigits = new int[10];\n        for (BigInteger number : numbers) {\n            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n        }\n\n        for (int i = 1; i < firstDigits.length; i++) {\n            System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n        }\n    }\n}\n"}
{"id": 45439, "name": "Anonymous recursion", "VB": "Sub Main()\nDebug.Print F(-10)\nDebug.Print F(10)\nEnd Sub\n\nPrivate Function F(N As Long) As Variant\n    If N < 0 Then\n        F = \"Error. Negative argument\"\n    ElseIf N <= 1 Then\n        F = N\n    Else\n        F = F(N - 1) + F(N - 2)\n    End If\nEnd Function\n", "Java": "public static long fib(int n) {\n    if (n < 0)\n        throw new IllegalArgumentException(\"n can not be a negative number\");\n\n    return new Object() {\n        private long fibInner(int n) {\n            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));\n        }\n    }.fibInner(n);\n}\n"}
{"id": 45440, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 45441, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 45442, "name": "Substring_Top and tail", "VB": "string = \"Small Basic\"\nTextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) \nTextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) \nTextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) \n", "Java": "String strOrig = 'brooms';\nString str1 = strOrig.substring(1, strOrig.length());\nsystem.debug(str1);\nString str2 = strOrig.substring(0, strOrig.length()-1);\nsystem.debug(str2);\nString str3 = strOrig.substring(1, strOrig.length()-1);\nsystem.debug(str3);\n\n\nString strOrig = 'brooms';\nString str1 = strOrig.replaceAll( '^.', '' );\nsystem.debug(str1);\nString str2 = strOrig.replaceAll( '.$', '' ) ;\nsystem.debug(str2);\nString str3 = strOrig.replaceAll( '^.|.$', '' );\nsystem.debug(str3);\n"}
{"id": 45443, "name": "Longest string challenge", "VB": "\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_\n\t\"\\input.txt\",1)\n\nlist = \"\"\nprevious_line = \"\"\nl = Len(previous_line)\n\nDo Until objfile.AtEndOfStream\n\tcurrent_line = objfile.ReadLine\n\tIf Mid(current_line,l+1,1) <> \"\" Then\n\t\tlist = current_line & vbCrLf\n\t\tprevious_line = current_line\n\t\tl = Len(previous_line)\n\tElseIf Mid(current_line,l,1) <> \"\"  And Mid(current_line,(l+1),1) = \"\" Then\n\t\tlist = list & current_line & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo list\n\nobjfile.Close\nSet objfso = Nothing\n", "Java": "import java.io.File;\nimport java.util.Scanner;\n\npublic class LongestStringChallenge {\n\n    public static void main(String[] args) throws Exception {\n        String lines = \"\", longest = \"\";\n        try (Scanner sc = new Scanner(new File(\"lines.txt\"))) {\n            while(sc.hasNext()) {\n                String line = sc.nextLine();\n                if (longer(longest, line))\n                    lines = longest = line;\n                else if (!longer(line, longest))\n                    lines = lines.concat(\"\\n\").concat(line);\n            }\n        }\n        System.out.println(lines);\n    }\n\n    static boolean longer(String a, String b) {\n        try {\n            String dummy = a.substring(b.length());\n        } catch (StringIndexOutOfBoundsException e) {\n            return true;\n        }\n        return false;\n    }\n}\n"}
{"id": 45444, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n"}
{"id": 45445, "name": "Universal Turing machine", "VB": "Option Base 1\nPublic Enum sett\n    name_ = 1\n    initState\n    endState\n    blank\n    rules\nEnd Enum\nPublic incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant\n\nPrivate Sub init()\n    incrementer = Array(\"Simple incrementer\", _\n        \"q0\", _\n        \"qf\", _\n        \"B\", _\n         Array( _\n         Array(\"q0\", \"1\", \"1\", \"right\", \"q0\"), _\n         Array(\"q0\", \"B\", \"1\", \"stay\", \"qf\")))\n    threeStateBB = Array(\"Three-state busy beaver\", _\n       \"a\", _\n       \"halt\", _\n       \"0\", _\n        Array( _\n        Array(\"a\", \"0\", \"1\", \"right\", \"b\"), _\n        Array(\"a\", \"1\", \"1\", \"left\", \"c\"), _\n        Array(\"b\", \"0\", \"1\", \"left\", \"a\"), _\n        Array(\"b\", \"1\", \"1\", \"right\", \"b\"), _\n        Array(\"c\", \"0\", \"1\", \"left\", \"b\"), _\n        Array(\"c\", \"1\", \"1\", \"stay\", \"halt\")))\n    fiveStateBB = Array(\"Five-state busy beaver\", _\n        \"A\", _\n        \"H\", _\n        \"0\", _\n         Array( _\n         Array(\"A\", \"0\", \"1\", \"right\", \"B\"), _\n         Array(\"A\", \"1\", \"1\", \"left\", \"C\"), _\n         Array(\"B\", \"0\", \"1\", \"right\", \"C\"), _\n         Array(\"B\", \"1\", \"1\", \"right\", \"B\"), _\n         Array(\"C\", \"0\", \"1\", \"right\", \"D\"), _\n         Array(\"C\", \"1\", \"0\", \"left\", \"E\"), _\n         Array(\"D\", \"0\", \"1\", \"left\", \"A\"), _\n         Array(\"D\", \"1\", \"1\", \"left\", \"D\"), _\n         Array(\"E\", \"0\", \"1\", \"stay\", \"H\"), _\n         Array(\"E\", \"1\", \"0\", \"left\", \"A\")))\nEnd Sub\n\nPrivate Sub show(state As String, headpos As Long, tape As Collection)\n    Debug.Print \" \"; state; String$(7 - Len(state), \" \"); \"| \";\n    For p = 1 To tape.Count\n        Debug.Print IIf(p = headpos, \"[\" & tape(p) & \"]\", \" \" & tape(p) & \" \");\n    Next p\n    Debug.Print\nEnd Sub\n \n\nPrivate Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0)\n    Dim state As String: state = machine(initState)\n    Dim headpos As Long: headpos = 1\n    Dim counter As Long, rule As Variant\n    Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), \"=\")\n    If Not countOnly Then Debug.Print \" State  | Tape [head]\" & vbCrLf & \"---------------------\"\n    Do While True\n        If headpos > tape.Count Then\n            tape.Add machine(blank)\n        Else\n            If headpos < 1 Then\n                tape.Add machine(blank), Before:=1\n                headpos = 1\n            End If\n        End If\n        If Not countOnly Then show state, headpos, tape\n        For i = LBound(machine(rules)) To UBound(machine(rules))\n            rule = machine(rules)(i)\n            If rule(1) = state And rule(2) = tape(headpos) Then\n                tape.Remove headpos\n                If headpos > tape.Count Then\n                    tape.Add rule(3)\n                Else\n                    tape.Add rule(3), Before:=headpos\n                End If\n                If rule(4) = \"left\" Then headpos = headpos - 1\n                If rule(4) = \"right\" Then headpos = headpos + 1\n                state = rule(5)\n                Exit For\n            End If\n        Next i\n        counter = counter + 1\n        If counter Mod 100000 = 0 Then\n            Debug.Print counter\n            DoEvents\n            DoEvents\n        End If\n        If state = machine(endState) Then Exit Do\n    Loop\n    DoEvents\n    If countOnly Then\n        Debug.Print \"Steps taken: \", counter\n    Else\n        show state, headpos, tape\n        Debug.Print\n    End If\nEnd Sub\n \nPublic Sub main()\n    init\n    Dim tap As New Collection\n    tap.Add \"1\": tap.Add \"1\": tap.Add \"1\"\n    UTM incrementer, tap\n    Set tap = New Collection\n    UTM threeStateBB, tap\n    Set tap = New Collection\n    UTM fiveStateBB, tap, countOnly:=-1\nEnd Sub\n", "Java": "import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.ListIterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Map;\n\npublic class UTM {\n    private List<String> tape;\n    private String blankSymbol;\n    private ListIterator<String> head;\n    private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();\n    private Set<String> terminalStates;\n    private String initialState;\n    \n    public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {\n        this.blankSymbol = blankSymbol;\n        for (Transition t : transitions) {\n            this.transitions.put(t.from, t);\n        }\n        this.terminalStates = terminalStates;\n        this.initialState = initialState;\n    }\n    \n    public static class StateTapeSymbolPair {\n        private String state;\n        private String tapeSymbol;\n\n        public StateTapeSymbolPair(String state, String tapeSymbol) {\n            this.state = state;\n            this.tapeSymbol = tapeSymbol;\n        }\n\n        \n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result\n                    + ((state == null) ? 0 : state.hashCode());\n            result = prime\n                    * result\n                    + ((tapeSymbol == null) ? 0 : tapeSymbol\n                            .hashCode());\n            return result;\n        }\n\n        \n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            StateTapeSymbolPair other = (StateTapeSymbolPair) obj;\n            if (state == null) {\n                if (other.state != null)\n                    return false;\n            } else if (!state.equals(other.state))\n                return false;\n            if (tapeSymbol == null) {\n                if (other.tapeSymbol != null)\n                    return false;\n            } else if (!tapeSymbol.equals(other.tapeSymbol))\n                return false;\n            return true;\n        }\n\n        @Override\n        public String toString() {\n            return \"(\" + state + \",\" + tapeSymbol + \")\";\n        }\n    }\n    \n    public static class Transition {\n        private StateTapeSymbolPair from;\n        private StateTapeSymbolPair to;\n        private int direction; \n\n        public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {\n             this.from = from;\n            this.to = to;\n            this.direction = direction;\n        }\n\n        @Override\n        public String toString() {\n            return from + \"=>\" + to + \"/\" + direction;\n        }\n    }\n    \n    public void initializeTape(List<String> input) { \n        tape = input;\n    }\n    \n    public void initializeTape(String input) { \n        tape = new LinkedList<String>();\n        for (int i = 0; i < input.length(); i++) {\n            tape.add(input.charAt(i) + \"\");\n        }\n    }\n    \n    public List<String> runTM() { \n        if (tape.size() == 0) {\n            tape.add(blankSymbol);\n        }\n        \n        head = tape.listIterator();\n        head.next();\n        head.previous();\n        \n        StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));\n        \n        while (transitions.containsKey(tsp)) { \n            System.out.println(this + \" --- \" + transitions.get(tsp));\n            Transition trans = transitions.get(tsp);\n            head.set(trans.to.tapeSymbol); \n            tsp.state = trans.to.state; \n            if (trans.direction == -1) { \n                if (!head.hasPrevious()) {\n                    head.add(blankSymbol); \n                }\n                tsp.tapeSymbol = head.previous(); \n            } else if (trans.direction == 1) { \n                head.next();\n                if (!head.hasNext()) {\n                    head.add(blankSymbol); \n                    head.previous();\n                }\n                tsp.tapeSymbol = head.next(); \n                head.previous();\n            } else {\n                tsp.tapeSymbol = trans.to.tapeSymbol;\n            }\n        }\n        \n        System.out.println(this + \" --- \" + tsp);\n        \n        if (terminalStates.contains(tsp.state)) {\n            return tape;\n        } else {\n            return null;\n        }\n    }\n\n    @Override\n    public String toString() {\n        try {\n        \tint headPos = head.previousIndex();\n            String s = \"[ \";\n            \n            for (int i = 0; i <= headPos; i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            s += \"[H] \";\n            \n            for (int i = headPos + 1; i < tape.size(); i++) {\n                s += tape.get(i) + \" \";\n            }\n\n            return s + \"]\";\n        } catch (Exception e) {\n            return \"\";\n        }\n    }\n    \n    public static void main(String[] args) {\n        \n        String init = \"q0\";\n        String blank = \"b\";\n        \n        Set<String> term = new HashSet<String>();\n        term.add(\"qf\");\n        \n        Set<Transition> trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"1\"), new StateTapeSymbolPair(\"q0\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"q0\", \"b\"), new StateTapeSymbolPair(\"qf\", \"1\"), 0));\n        \n        UTM machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"111\");\n        System.out.println(\"Output (si): \" + machine.runTM() + \"\\n\");\n        \n        \n        init = \"a\";\n        \n        term.clear();\n        term.add(\"halt\");\n        \n        blank = \"0\";\n        \n        trans.clear();\n\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"a\", \"1\"), new StateTapeSymbolPair(\"c\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"0\"), new StateTapeSymbolPair(\"a\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"b\", \"1\"), new StateTapeSymbolPair(\"b\", \"1\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"0\"), new StateTapeSymbolPair(\"b\", \"1\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"c\", \"1\"), new StateTapeSymbolPair(\"halt\", \"1\"), 0));\n        \n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"\");\n        System.out.println(\"Output (bb): \" + machine.runTM());\n\n        \n        init = \"s0\";\n        blank = \"*\";\n        \n        term = new HashSet<String>();\n        term.add(\"see\");\n        \n        trans = new HashSet<Transition>();\n        \n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"a\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"b\"), new StateTapeSymbolPair(\"s1\", \"B\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s0\", \"*\"), new StateTapeSymbolPair(\"se\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"a\"), new StateTapeSymbolPair(\"s1\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"b\"), new StateTapeSymbolPair(\"s1\", \"b\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s1\", \"*\"), new StateTapeSymbolPair(\"s2\", \"*\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"a\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"b\"), new StateTapeSymbolPair(\"s2\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s2\", \"B\"), new StateTapeSymbolPair(\"se\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"a\"), new StateTapeSymbolPair(\"s3\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"b\"), new StateTapeSymbolPair(\"s3\", \"b\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"s3\", \"B\"), new StateTapeSymbolPair(\"s0\", \"a\"), 1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"a\"), new StateTapeSymbolPair(\"se\", \"a\"), -1));\n        trans.add(new Transition(new StateTapeSymbolPair(\"se\", \"*\"), new StateTapeSymbolPair(\"see\", \"*\"), 1));\n\n        machine = new UTM(trans, term, init, blank);\n        machine.initializeTape(\"babbababaa\");\n        System.out.println(\"Output (sort): \" + machine.runTM() + \"\\n\");\n    }\n}\n"}
{"id": 45446, "name": "Create a file", "VB": "Public Sub create_file()\n    Dim FileNumber As Integer\n    FileNumber = FreeFile\n    MkDir \"docs\"\n    Open \"docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\n    MkDir \"C:\\docs\"\n    Open \"C:\\docs\\output.txt\" For Output As #FreeFile\n    Close #FreeFile\nEnd Sub\n", "Java": "import java.io.*;\npublic class CreateFileTest {\n\tpublic static void main(String args[]) {\n\t\ttry {\n\t\t\tnew File(\"output.txt\").createNewFile();\n\t\t\tnew File(File.separator + \"output.txt\").createNewFile();\n\t\t\tnew File(\"docs\").mkdir();\n\t\t\tnew File(File.separator + \"docs\").mkdir();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t}\n\t}\n}\n"}
{"id": 45447, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 45448, "name": "Bioinformatics_base count", "VB": "b=_  \n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" &_\n\"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" &_\n\"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" &_\n\"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" &_\n\"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" &_\n\"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" &_\n\"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" &_\n\"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" &_\n\"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" &_\n\"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\ns=\"SEQUENCE:\"\nacnt=0:ccnt=0:gcnt=0:tcnt=0\n \nfor i=0 to len(b)-1\n  if (i mod 30)=0 then s = s & vbcrlf & right(\"   \"& i+1,3)&\": \" \n  if (i mod 5)=0 then s=s& \" \"\n  m=mid(b,i+1,1)  \n  s=s & m\n  select case m\n  case \"A\":acnt=acnt+1\n  case \"C\":ccnt=ccnt+1\n  case \"G\":gcnt=gcnt+1\n  case \"T\":tcnt=tcnt+1\n  case else\n     wscript.echo \"error at \",i+1, m \n  end select\nnext  \nwscript.echo s & vbcrlf\nwscript.echo \"Count: A=\"&acnt & \" C=\" & ccnt & \" G=\" & gcnt & \" T=\" & tcnt\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n    public static void main(String[] args) {\n        Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n        gene.runSequence();\n    }\n}\n\n\npublic class Sequence {\n    \n    private final String seq;\n    \n    public Sequence(String sq) {\n        this.seq = sq;\n    }\n    \n    \n    public void prettyPrint() {\n        System.out.println(\"Sequence:\");\n        int i = 0;\n        for ( ; i < seq.length() - 50 ; i += 50) {\n            System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n        }\n        System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n    }\n    \n    \n    public void displayCount() {\n        Map<Character, Integer> counter = new HashMap<>();\n        for (int i = 0 ; i < seq.length() ; ++i) {\n            counter.merge(seq.charAt(i), 1, Integer::sum);\n        }\n\n        System.out.println(\"Base vs. Count:\");\n        counter.forEach(\n            key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n        System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n    }\n    \n    public void runSequence() {\n        this.prettyPrint();\n        this.displayCount();\n    }\n}\n"}
{"id": 45449, "name": "Dining philosophers", "VB": "\n\n\n\n\nPublic Const HOLDON = False\nPublic Const DIJKSTRASOLUTION = True\nPublic Const X = 10 \nPublic Const GETS = 0\nPublic Const PUTS = 1\nPublic Const EATS = 2\nPublic Const THKS = 5\nPublic Const FRSTFORK = 0\nPublic Const SCNDFORK = 1\nPublic Const SPAGHETI = 0\nPublic Const UNIVERSE = 1\nPublic Const MAXCOUNT = 100000\nPublic Const PHILOSOPHERS = 5\nPublic semaphore(PHILOSOPHERS - 1) As Integer\nPublic positi0n(1, PHILOSOPHERS - 1) As Integer\nPublic programcounter(PHILOSOPHERS - 1) As Long\nPublic statistics(PHILOSOPHERS - 1, 5, 1) As Long\nPublic names As Variant\nPrivate Sub init()\n    names = [{\"Aquinas\",\"Babbage\",\"Carroll\",\"Derrida\",\"Erasmus\"}]\n    For j = 0 To PHILOSOPHERS - 2\n        positi0n(0, j) = j + 1 \n        positi0n(1, j) = j     \n    Next j\n    If DIJKSTRASOLUTION Then\n        positi0n(0, PHILOSOPHERS - 1) = j \n        positi0n(1, PHILOSOPHERS - 1) = 0 \n    Else\n        positi0n(0, PHILOSOPHERS - 1) = 0 \n        positi0n(1, PHILOSOPHERS - 1) = j \n    End If\nEnd Sub\nPrivate Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)\n    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1\n    If verb < 2 Then\n        If semaphore(positi0n(objekt, subject)) <> verb Then\n            If Not HOLDON Then\n                \n                \n                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt\n                \n                programcounter(subject) = 0\n            End If\n        Else\n            \n            semaphore(positi0n(objekt, subject)) = 1 - verb\n            programcounter(subject) = (programcounter(subject) + 1) Mod 6\n        End If\n    Else\n        \n        \n        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6\n    End If\nEnd Sub\nPrivate Sub dine()\n    Dim ph As Integer\n    Do While TC < MAXCOUNT\n        For ph = 0 To PHILOSOPHERS - 1\n            Select Case programcounter(ph)\n                Case 0: philosopher ph, GETS, FRSTFORK\n                Case 1: philosopher ph, GETS, SCNDFORK\n                Case 2: philosopher ph, EATS, SPAGHETI\n                Case 3: philosopher ph, PUTS, FRSTFORK\n                Case 4: philosopher ph, PUTS, SCNDFORK\n                Case 5: philosopher ph, THKS, UNIVERSE\n            End Select\n            TC = TC + 1\n        Next ph\n    Loop\nEnd Sub\nPrivate Sub show()\n    Debug.Print \"Stats\", \"Gets\", \"Gets\", \"Eats\", \"Puts\", \"Puts\", \"Thinks\"\n    Debug.Print \"\", \"First\", \"Second\", \"Spag-\", \"First\", \"Second\", \"About\"\n    Debug.Print \"\", \"Fork\", \"Fork\", \"hetti\", \"Fork\", \"Fork\", \"Universe\"\n    For subject = 0 To PHILOSOPHERS - 1\n        Debug.Print names(subject + 1),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, GETS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, EATS, SPAGHETI),\n        For objekt = 0 To 1\n            Debug.Print statistics(subject, PUTS, objekt),\n        Next objekt\n        Debug.Print statistics(subject, THKS, UNIVERSE)\n    Next subject\nEnd Sub\nPublic Sub main()\n    init\n    dine\n    show\nEnd Sub\n", "Java": "package diningphilosophers;\n\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nenum PhilosopherState { Get, Eat, Pon }\n\nclass Fork {\n    public static final int ON_TABLE = -1;\n    static int instances = 0;\n    public int id;\n    public AtomicInteger holder = new AtomicInteger(ON_TABLE);\n\n    Fork() { id = instances++; }\n}\n\nclass Philosopher implements Runnable {\n    static final int maxWaitMs = 100;                          \n    static AtomicInteger token = new AtomicInteger(0);\n    static int instances = 0;\n    static Random rand = new Random();\n    AtomicBoolean end = new AtomicBoolean(false);\n    int id;\n    PhilosopherState state = PhilosopherState.Get;\n    Fork left;\n    Fork right;\n    int timesEaten = 0;\n\n    Philosopher() {\n        id = instances++;\n        left = Main.forks.get(id);\n        right = Main.forks.get((id+1)%Main.philosopherCount);\n    }\n\n    void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }\n        catch (InterruptedException ex) {} }\n\n    void waitForFork(Fork fork) {\n        do {\n            if (fork.holder.get() == Fork.ON_TABLE) {\n                fork.holder.set(id);                \n                return;\n            } else {                                \n                sleep();                            \n            }\n        } while (true);\n    }\n\n    public void run() {\n        do {\n            if (state == PhilosopherState.Pon) {    \n                state = PhilosopherState.Get;       \n            } else { \n                if (token.get() == id) {            \n                    waitForFork(left);\n                    waitForFork(right);             \n                    token.set((id+2)% Main.philosopherCount);\n                    state = PhilosopherState.Eat;\n                    timesEaten++;\n                    sleep();                        \n                    left.holder.set(Fork.ON_TABLE);\n                    right.holder.set(Fork.ON_TABLE);\n                    state = PhilosopherState.Pon;   \n                    sleep();\n                } else {                    \n                    sleep();\n                }\n            }\n        } while (!end.get());\n    }\n}\n\npublic class Main {\n    static final int philosopherCount = 5; \n    static final int runSeconds = 15;\n    static ArrayList<Fork> forks = new ArrayList<Fork>();\n    static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();\n\n    public static void main(String[] args) {\n        for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());\n        for (int i = 0 ; i < philosopherCount ; i++)\n            philosophers.add(new Philosopher());\n        for (Philosopher p : philosophers) new Thread(p).start();\n        long endTime = System.currentTimeMillis() + (runSeconds * 1000);\n\n        do {                                                    \n            StringBuilder sb = new StringBuilder(\"|\");\n\n            for (Philosopher p : philosophers) {\n                sb.append(p.state.toString());\n                sb.append(\"|\");            \n            }                              \n\n            sb.append(\"     |\");\n\n            for (Fork f : forks) {\n                int holder = f.holder.get();\n                sb.append(holder==-1?\"   \":String.format(\"P%02d\",holder));\n                sb.append(\"|\");\n            }\n            \n            System.out.println(sb.toString());\n            try {Thread.sleep(1000);} catch (Exception ex) {}\n        } while (System.currentTimeMillis() < endTime);\n\n        for (Philosopher p : philosophers) p.end.set(true);\n        for (Philosopher p : philosophers)\n            System.out.printf(\"P%02d: ate %,d times, %,d/sec\\n\",\n                p.id, p.timesEaten, p.timesEaten/runSeconds);\n    }\n}\n"}
{"id": 45450, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 45451, "name": "Factorions", "VB": "\n    Dim fact()\n\tnn1=9 : nn2=12\n\tlim=1499999\n    ReDim fact(nn2)\n\tfact(0)=1\n\tFor i=1 To nn2\n\t\tfact(i)=fact(i-1)*i\n\tNext\n\tFor base=nn1 To nn2\n\t\tlist=\"\"\n\t\tFor i=1 To lim\n\t\t\ts=0\n\t\t\tt=i\n\t\t\tDo While t<>0\n\t\t\t\td=t Mod base\n\t\t\t\ts=s+fact(d)\n\t\t\t\tt=t\\base\n\t\t\tLoop\n\t\t\tIf s=i Then list=list &\" \"& i\n\t\tNext\n\t\tWscript.Echo \"the factorions for base \"& right(\" \"& base,2) &\" are: \"& list\n\tNext\n", "Java": "public class Factorion {\n    public static void main(String [] args){\n        System.out.println(\"Base 9:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,9);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 10:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,10);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 11:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,11);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n        System.out.println(\"\\nBase 12:\");\n        for(int i = 1; i <= 1499999; i++){\n            String iStri = String.valueOf(i);\n            int multiplied = operate(iStri,12);\n            if(multiplied == i){\n                System.out.print(i + \"\\t\");\n            }\n        }\n    }\n    public static int factorialRec(int n){\n        int result = 1;\n        return n == 0 ? result : result * n * factorialRec(n-1);\n    }\n\n    public static int operate(String s, int base){\n        int sum = 0;\n        String strx = fromDeci(base, Integer.parseInt(s));\n        for(int i = 0; i < strx.length(); i++){\n            if(strx.charAt(i) == 'A'){\n                sum += factorialRec(10);\n            }else if(strx.charAt(i) == 'B') {\n                sum += factorialRec(11);\n            }else if(strx.charAt(i) == 'C') {\n                sum += factorialRec(12);\n            }else {\n                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));\n            }\n        }\n        return sum;\n    }\n    \n    static char reVal(int num) {\n        if (num >= 0 && num <= 9)\n            return (char)(num + 48);\n        else\n            return (char)(num - 10 + 65);\n    }\n    static String fromDeci(int base, int num){\n        StringBuilder s = new StringBuilder();\n        while (num > 0) {\n            s.append(reVal(num % base));\n            num /= base;\n        }\n        return new String(new StringBuilder(s).reverse());\n    }\n}\n"}
{"id": 45452, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 45453, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 45454, "name": "Abbreviations, easy", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n    s = s & \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n    s = s & \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n    s = s & \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n    s = s & \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n    s = s & \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n    s = s & \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer\n    For Each word In commandtable\n        If Len(word) > 0 Then\n            i = 1\n            Do While Mid(word, i, 1) >= \"A\" And Mid(word, i, 1) <= \"Z\"\n                i = i + 1\n            Loop\n            command_table.Add Key:=word, Item:=i - 1\n        End If\n    Next word\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n    private static final Scanner input = new Scanner(System.in);\n    private static final String  COMMAND_TABLE\n            =       \"  Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy\\n\" +\n                    \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n                    \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n                    \" Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO\\n\" +\n                    \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT\\n\" +\n                    \" READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT\\n\" +\n                    \" RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus TOP TRAnsfer Type Up\";\n\n    public static void main(String[] args) {\n        String[]             cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n        Map<String, Integer> cmd_table   = new HashMap<String, Integer>();\n\n        for (String word : cmdTableArr) {  \n            cmd_table.put(word, countCaps(word));\n        }\n\n        System.out.print(\"Please enter your command to verify: \");\n        String   userInput  = input.nextLine();\n        String[] user_input = userInput.split(\"\\\\s+\");\n\n        for (String s : user_input) {\n            boolean match = false; \n            for (String cmd : cmd_table.keySet()) {\n                if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n                    String temp = cmd.toUpperCase();\n                    if (temp.startsWith(s.toUpperCase())) {\n                        System.out.print(temp + \" \");\n                        match = true;\n                    }\n                }\n            }\n            if (!match) { \n                System.out.print(\"*error* \");\n            }\n        }\n    }\n\n    private static int countCaps(String word) {\n        int numCaps = 0;\n        for (int i = 0; i < word.length(); i++) {\n            if (Character.isUpperCase(word.charAt(i))) {\n                numCaps++;\n            }\n        }\n        return numCaps;\n    }\n}\n"}
{"id": 45455, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 45456, "name": "Bacon cipher", "VB": "Imports System.Text\n\nModule Module1\n\n    ReadOnly CODES As New Dictionary(Of Char, String) From {\n        {\"a\", \"AAAAA\"}, {\"b\", \"AAAAB\"}, {\"c\", \"AAABA\"}, {\"d\", \"AAABB\"}, {\"e\", \"AABAA\"},\n        {\"f\", \"AABAB\"}, {\"g\", \"AABBA\"}, {\"h\", \"AABBB\"}, {\"i\", \"ABAAA\"}, {\"j\", \"ABAAB\"},\n        {\"k\", \"ABABA\"}, {\"l\", \"ABABB\"}, {\"m\", \"ABBAA\"}, {\"n\", \"ABBAB\"}, {\"o\", \"ABBBA\"},\n        {\"p\", \"ABBBB\"}, {\"q\", \"BAAAA\"}, {\"r\", \"BAAAB\"}, {\"s\", \"BAABA\"}, {\"t\", \"BAABB\"},\n        {\"u\", \"BABAA\"}, {\"v\", \"BABAB\"}, {\"w\", \"BABBA\"}, {\"x\", \"BABBB\"}, {\"y\", \"BBAAA\"},\n        {\"z\", \"BBAAB\"}, {\" \", \"BBBAA\"} \n    }\n\n    Function Encode(plainText As String, message As String) As String\n        Dim pt = plainText.ToLower()\n        Dim sb As New StringBuilder()\n        For Each c In pt\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(CODES(c))\n            Else\n                sb.Append(CODES(\" \"))\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        Dim mg = message.ToLower() \n\n        sb.Length = 0\n        Dim count = 0\n        For Each c In mg\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                If et(count) = \"A\" Then\n                    sb.Append(c)\n                Else\n                    sb.Append(Chr(Asc(c) - 32)) \n                End If\n                count += 1\n                If count = et.Length Then\n                    Exit For\n                End If\n            Else\n                sb.Append(c)\n            End If\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Function Decode(message As String) As String\n        Dim sb As New StringBuilder\n\n        For Each c In message\n            If \"a\" <= c AndAlso c <= \"z\" Then\n                sb.Append(\"A\")\n            ElseIf \"A\" <= c AndAlso c <= \"Z\" Then\n                sb.Append(\"B\")\n            End If\n        Next\n\n        Dim et = sb.ToString()\n        sb.Length = 0\n        For index = 0 To et.Length - 1 Step 5\n            Dim quintet = et.Substring(index, 5)\n            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key\n            sb.Append(key)\n        Next\n\n        Return sb.ToString()\n    End Function\n\n    Sub Main()\n        Dim plainText = \"the quick brown fox jumps over the lazy dog\"\n        Dim message =\n            \"bacon\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\"\n\n        Dim cipherText = Encode(plainText, message)\n        Console.WriteLine(\"Cipher text ->\" & Environment.NewLine & \"{0}\", cipherText)\n\n        Dim decodedText = Decode(cipherText)\n        Console.WriteLine(Environment.NewLine & \"Hidden text ->\" & Environment.NewLine & \"{0}\", decodedText)\n    End Sub\n\nEnd Module\n", "Java": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\n\npublic class BaconCipher {\n    private static final Map<Character, String> codes;\n\n    static {\n        codes = new HashMap<>();\n        codes.putAll(Map.of(\n            'a', \"AAAAA\", 'b', \"AAAAB\", 'c', \"AAABA\", 'd', \"AAABB\", 'e', \"AABAA\",\n            'f', \"AABAB\", 'g', \"AABBA\", 'h', \"AABBB\", 'i', \"ABAAA\", 'j', \"ABAAB\"\n        ));\n        codes.putAll(Map.of(\n            'k', \"ABABA\", 'l', \"ABABB\", 'm', \"ABBAA\", 'n', \"ABBAB\", 'o', \"ABBBA\",\n            'p', \"ABBBB\", 'q', \"BAAAA\", 'r', \"BAAAB\", 's', \"BAABA\", 't', \"BAABB\"\n        ));\n        codes.putAll(Map.of(\n            'u', \"BABAA\", 'v', \"BABAB\", 'w', \"BABBA\", 'x', \"BABBB\", 'y', \"BBAAA\",\n            'z', \"BBAAB\", ' ', \"BBBAA\" \n        ));\n    }\n\n    private static String encode(String plainText, String message) {\n        String pt = plainText.toLowerCase();\n        StringBuilder sb = new StringBuilder();\n        for (char c : pt.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append(codes.get(c));\n            else sb.append(codes.get(' '));\n        }\n        String et = sb.toString();\n        String mg = message.toLowerCase();  \n        sb.setLength(0);\n        int count = 0;\n        for (char c : mg.toCharArray()) {\n            if ('a' <= c && c <= 'z') {\n                if (et.charAt(count) == 'A') sb.append(c);\n                else sb.append(((char) (c - 32))); \n                count++;\n                if (count == et.length()) break;\n            } else sb.append(c);\n        }\n        return sb.toString();\n    }\n\n    private static String decode(String message) {\n        StringBuilder sb = new StringBuilder();\n        for (char c : message.toCharArray()) {\n            if ('a' <= c && c <= 'z') sb.append('A');\n            if ('A' <= c && c <= 'Z') sb.append('B');\n        }\n        String et = sb.toString();\n        sb.setLength(0);\n        for (int i = 0; i < et.length(); i += 5) {\n            String quintet = et.substring(i, i + 5);\n            Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);\n            sb.append(key);\n        }\n        return sb.toString();\n    }\n\n    public static void main(String[] args) {\n        String plainText = \"the quick brown fox jumps over the lazy dog\";\n        String message = \"bacon's cipher is a method of steganography created by francis bacon. \" +\n            \"this task is to implement a program for encryption and decryption of \" +\n            \"plaintext using the simple alphabet of the baconian cipher or some \" +\n            \"other kind of representation of this alphabet (make anything signify anything). \" +\n            \"the baconian alphabet may optionally be extended to encode all lower \" +\n            \"case characters individually and/or adding a few punctuation characters \" +\n            \"such as the space.\";\n        String cipherText = encode(plainText, message);\n        System.out.printf(\"Cipher text ->\\n\\n%s\\n\", cipherText);\n        String decodedText = decode(cipherText);\n        System.out.printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText);\n    }\n}\n"}
{"id": 45457, "name": "Spiral matrix", "VB": "Function build_spiral(n)\n\tbotcol = 0 : topcol = n - 1\n\tbotrow = 0 : toprow = n - 1\n\t\n\tDim matrix()\n\tReDim matrix(topcol,toprow)\n\tdir = 0 : col = 0 : row = 0\n\t\n\tFor i = 0 To n*n-1\n\t\tmatrix(col,row) = i\n\t\tSelect Case dir\n\t\t\tCase 0\n\t\t\t\tIf col < topcol Then\n\t\t\t\t\tcol = col + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 1 : row = row + 1 : botrow = botrow + 1\n\t\t\t\tEnd If\n\t\t\tCase 1\n\t\t\t\tIf row < toprow Then\n\t\t\t\t\trow = row + 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 2 : col = col - 1 : topcol = topcol - 1\t\n\t\t\t\tEnd If\n\t\t\tCase 2\n\t\t\t\tIf col > botcol Then\n\t\t\t\t\tcol = col - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 3 : row = row - 1 : toprow = toprow - 1\n\t\t\t\tEnd If\n\t\t\tCase 3\n\t\t\t\tIf row > botrow Then\n\t\t\t\t\trow = row - 1\n\t\t\t\tElse\n\t\t\t\t\tdir = 0 : col = col + 1 : botcol = botcol + 1\n\t\t\t\tEnd If\n\t\tEnd Select\n\tNext\n\t\n\tFor y = 0 To n-1\n\t\tFor x = 0 To n-1\n\t\t\tWScript.StdOut.Write matrix(x,y) & vbTab\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n\nbuild_spiral(CInt(WScript.Arguments(0)))\n", "Java": "public class Blah {\n\n  public static void main(String[] args) {\n    print2dArray(getSpiralArray(5));\n  }\n\n  public static int[][] getSpiralArray(int dimension) {\n    int[][] spiralArray = new int[dimension][dimension];\n\n    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);\n\n    int j;\n    int sideLen = dimension;\n    int currNum = 0;\n\n    for (int i = 0; i < numConcentricSquares; i++) {\n      \n      for (j = 0; j < sideLen; j++) {\n        spiralArray[i][i + j] = currNum++;\n      }\n\n      \n      for (j = 1; j < sideLen; j++) {\n        spiralArray[i + j][dimension - 1 - i] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > -1; j--) {\n        spiralArray[dimension - 1 - i][i + j] = currNum++;\n      }\n\n      \n      for (j = sideLen - 2; j > 0; j--) {\n        spiralArray[i + j][i] = currNum++;\n      }\n\n      sideLen -= 2;\n    }\n\n    return spiralArray;\n  }\n\n  public static void print2dArray(int[][] array) {\n    for (int[] row : array) {\n      for (int elem : row) {\n        System.out.printf(\"%3d\", elem);\n      }\n      System.out.println();\n    }\n  }\n}\n"}
{"id": 45458, "name": "Optional parameters", "VB": "Private Sub optional_parameters(theRange As String, _\n        Optional ordering As Integer = 0, _\n        Optional column As Integer = 1, _\n        Optional reverse As Integer = 1)\n    ActiveSheet.Sort.SortFields.Clear\n    ActiveSheet.Sort.SortFields.Add _\n        Key:=Range(theRange).Columns(column), _\n        SortOn:=SortOnValues, _\n        Order:=reverse, _\n        DataOption:=ordering \n    With ActiveSheet.Sort\n        .SetRange Range(theRange)\n        .Header = xlGuess\n        .MatchCase = False\n        .Orientation = xlTopToBottom\n        .SortMethod = xlPinYin\n        .Apply\n    End With\nEnd Sub\nPublic Sub main()\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    optional_parameters theRange:=\"A1:C4\", ordering:=1, column:=2, reverse:=1\nEnd Sub\n", "Java": "module OptionalParameters\n    {\n    typedef Type<String  >.Orderer as ColumnOrderer;\n    typedef Type<String[]>.Orderer as RowOrderer;\n\n    static String[][] sort(String[][]     table,\n                           ColumnOrderer? orderer = Null,\n                           Int            column  = 0,\n                           Boolean        reverse = False,\n                          )\n        {\n        \n        orderer ?:= (s1, s2) -> s1 <=> s2;\n\n        \n        ColumnOrderer byString = reverse\n                ? ((s1, s2) -> orderer(s1, s2).reversed)\n                : orderer;\n\n        \n        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);\n\n        return table.sorted(byColumn);\n        }\n\n    void run()\n        {\n        String[][] table =\n            [\n            [\"c\", \"x\", \"i\"],\n            [\"a\", \"y\", \"p\"],\n            [\"b\", \"z\", \"a\"],\n            ];\n\n        show(\"original input\", table);\n        show(\"by default sort on column 0\", sort(table));\n        show(\"by column 2\", sort(table, column=2));\n        show(\"by column 2 reversed\", sort(table, column=2, reverse=True));\n        }\n\n    void show(String title, String[][] table)\n        {\n        @Inject Console console;\n        console.print($\"{title}:\");\n        for (val row : table)\n            {\n            console.print($\"  {row}\");\n            }\n        console.print();\n        }\n    }\n"}
{"id": 45459, "name": "Call a foreign-language function", "VB": "  Declare Function CreateFileW Lib \"Kernel32\" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _\n        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer\n  Declare Function WriteFile Lib \"Kernel32\" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _\n        overlapped As Ptr) As Boolean\n  Declare Function GetLastError Lib \"Kernel32\" () As Integer\n  Declare Function CloseHandle Lib \"kernel32\" (hObject As Integer) As Boolean\n  \n  Const FILE_SHARE_READ = &h00000001\n  Const FILE_SHARE_WRITE = &h00000002\n  Const OPEN_EXISTING = 3\n  \n  Dim fHandle As Integer = CreateFileW(\"C:\\foo.txt\", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n  If fHandle > 0 Then\n    Dim mb As MemoryBlock = \"Hello, World!\"\n    Dim bytesWritten As Integer\n    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then\n      MsgBox(\"Error Number: \" + Str(GetLastError))\n    End If\n    Call CloseHandle(fHandle)\n  Else\n    MsgBox(\"Error Number: \" + Str(GetLastError))\n  End If\n", "Java": "public class JNIDemo\n{\n  static\n  {  System.loadLibrary(\"JNIDemo\");  }\n  \n  public static void main(String[] args)\n  {\n    System.out.println(callStrdup(\"Hello World!\"));\n  }\n  \n  private static native String callStrdup(String s);\n}\n"}
{"id": 45460, "name": "Faulhaber's triangle", "VB": "Module Module1\n\n    Class Frac\n        Private ReadOnly num As Long\n        Private ReadOnly denom As Long\n\n        Public Shared ReadOnly ZERO = New Frac(0, 1)\n        Public Shared ReadOnly ONE = New Frac(1, 1)\n\n        Public Sub New(n As Long, d As Long)\n            If d = 0 Then\n                Throw New ArgumentException(\"d must not be zero\")\n            End If\n            Dim nn = n\n            Dim dd = d\n            If nn = 0 Then\n                dd = 1\n            ElseIf dd < 0 Then\n                nn = -nn\n                dd = -dd\n            End If\n            Dim g = Math.Abs(Gcd(nn, dd))\n            If g > 1 Then\n                nn /= g\n                dd /= g\n            End If\n            num = nn\n            denom = dd\n        End Sub\n\n        Private Shared Function Gcd(a As Long, b As Long) As Long\n            If b = 0 Then\n                Return a\n            Else\n                Return Gcd(b, a Mod b)\n            End If\n        End Function\n\n        Public Shared Operator -(self As Frac) As Frac\n            Return New Frac(-self.num, self.denom)\n        End Operator\n\n        Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom)\n        End Operator\n\n        Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac\n            Return lhs + -rhs\n        End Operator\n\n        Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac\n            Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom)\n        End Operator\n\n        Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x < y\n        End Operator\n\n        Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean\n            Dim x = lhs.num / lhs.denom\n            Dim y = rhs.num / rhs.denom\n            Return x > y\n        End Operator\n\n        Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom\n        End Operator\n\n        Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean\n            Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom\n        End Operator\n\n        Public Overrides Function ToString() As String\n            If denom = 1 Then\n                Return num.ToString\n            Else\n                Return String.Format(\"{0}/{1}\", num, denom)\n            End If\n        End Function\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim frac = CType(obj, Frac)\n            Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom\n        End Function\n    End Class\n\n    Function Bernoulli(n As Integer) As Frac\n        If n < 0 Then\n            Throw New ArgumentException(\"n may not be negative or zero\")\n        End If\n        Dim a(n + 1) As Frac\n        For m = 0 To n\n            a(m) = New Frac(1, m + 1)\n            For j = m To 1 Step -1\n                a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1)\n            Next\n        Next\n        \n        If n <> 1 Then\n            Return a(0)\n        Else\n            Return -a(0)\n        End If\n    End Function\n\n    Function Binomial(n As Integer, k As Integer) As Integer\n        If n < 0 OrElse k < 0 OrElse n < k Then\n            Throw New ArgumentException()\n        End If\n        If n = 0 OrElse k = 0 Then\n            Return 1\n        End If\n        Dim num = 1\n        For i = k + 1 To n\n            num *= i\n        Next\n        Dim denom = 1\n        For i = 2 To n - k\n            denom *= i\n        Next\n        Return num \\ denom\n    End Function\n\n    Function FaulhaberTriangle(p As Integer) As Frac()\n        Dim coeffs(p + 1) As Frac\n        For i = 1 To p + 1\n            coeffs(i - 1) = Frac.ZERO\n        Next\n        Dim q As New Frac(1, p + 1)\n        Dim sign = -1\n        For j = 0 To p\n            sign *= -1\n            coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j)\n        Next\n        Return coeffs\n    End Function\n\n    Sub Main()\n        For i = 1 To 10\n            Dim coeffs = FaulhaberTriangle(i - 1)\n            For Each coeff In coeffs\n                Console.Write(\"{0,5}  \", coeff)\n            Next\n            Console.WriteLine()\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Arrays;\nimport java.util.stream.LongStream;\n\npublic class FaulhabersTriangle {\n    private static final MathContext MC = new MathContext(256);\n\n    private static long gcd(long a, long b) {\n        if (b == 0) {\n            return a;\n        }\n        return gcd(b, a % b);\n    }\n\n    private static class Frac implements Comparable<Frac> {\n        private long num;\n        private long denom;\n\n        public static final Frac ZERO = new Frac(0, 1);\n\n        public Frac(long n, long d) {\n            if (d == 0) throw new IllegalArgumentException(\"d must not be zero\");\n            long nn = n;\n            long dd = d;\n            if (nn == 0) {\n                dd = 1;\n            } else if (dd < 0) {\n                nn = -nn;\n                dd = -dd;\n            }\n            long g = Math.abs(gcd(nn, dd));\n            if (g > 1) {\n                nn /= g;\n                dd /= g;\n            }\n            num = nn;\n            denom = dd;\n        }\n\n        public Frac plus(Frac rhs) {\n            return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);\n        }\n\n        public Frac unaryMinus() {\n            return new Frac(-num, denom);\n        }\n\n        public Frac minus(Frac rhs) {\n            return this.plus(rhs.unaryMinus());\n        }\n\n        public Frac times(Frac rhs) {\n            return new Frac(this.num * rhs.num, this.denom * rhs.denom);\n        }\n\n        @Override\n        public int compareTo(Frac o) {\n            double diff = toDouble() - o.toDouble();\n            return Double.compare(diff, 0.0);\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;\n        }\n\n        @Override\n        public String toString() {\n            if (denom == 1) {\n                return Long.toString(num);\n            }\n            return String.format(\"%d/%d\", num, denom);\n        }\n\n        public double toDouble() {\n            return (double) num / denom;\n        }\n\n        public BigDecimal toBigDecimal() {\n            return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);\n        }\n    }\n\n    private static Frac bernoulli(int n) {\n        if (n < 0) throw new IllegalArgumentException(\"n may not be negative or zero\");\n        Frac[] a = new Frac[n + 1];\n        Arrays.fill(a, Frac.ZERO);\n        for (int m = 0; m <= n; ++m) {\n            a[m] = new Frac(1, m + 1);\n            for (int j = m; j >= 1; --j) {\n                a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));\n            }\n        }\n        \n        if (n != 1) return a[0];\n        return a[0].unaryMinus();\n    }\n\n    private static long binomial(int n, int k) {\n        if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();\n        if (n == 0 || k == 0) return 1;\n        long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);\n        long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);\n        return num / den;\n    }\n\n    private static Frac[] faulhaberTriangle(int p) {\n        Frac[] coeffs = new Frac[p + 1];\n        Arrays.fill(coeffs, Frac.ZERO);\n        Frac q = new Frac(1, p + 1);\n        int sign = -1;\n        for (int j = 0; j <= p; ++j) {\n            sign *= -1;\n            coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));\n        }\n        return coeffs;\n    }\n\n    public static void main(String[] args) {\n        for (int i = 0; i <= 9; ++i) {\n            Frac[] coeffs = faulhaberTriangle(i);\n            for (Frac coeff : coeffs) {\n                System.out.printf(\"%5s  \", coeff);\n            }\n            System.out.println();\n        }\n        System.out.println();\n        \n        int k = 17;\n        Frac[] cc = faulhaberTriangle(k);\n        int n = 1000;\n        BigDecimal nn = BigDecimal.valueOf(n);\n        BigDecimal np = BigDecimal.ONE;\n        BigDecimal sum = BigDecimal.ZERO;\n        for (Frac c : cc) {\n            np = np.multiply(nn);\n            sum = sum.add(np.multiply(c.toBigDecimal()));\n        }\n        System.out.println(sum.toBigInteger());\n    }\n}\n"}
{"id": 45461, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 45462, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 45463, "name": "Command-line arguments", "VB": "Function Run(args() as String) As Integer\n  For each arg As String In args\n    Stdout.WriteLine(arg)\n  Next\nEnd Function\n", "Java": "public class Arguments {\n  public static void main(String[] args) {\n     System.out.println(\"There are \" + args.length + \" arguments given.\");\n     for(int i = 0; i < args.length; i++) \n        System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n  }\n}\n"}
{"id": 45464, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 45465, "name": "Array concatenation", "VB": "DEFINT A(1 to 4) = {1, 2, 3, 4}\nDEFINT B(1 to 4) = {10, 20, 30, 40}\n\n\nRedim A(1 to 8) as integer\nMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)\n", "Java": "String[] fruits = [\"apples\", \"oranges\"];\nString[] grains = [\"wheat\", \"corn\"];\nString[] all    = fruits + grains;\n"}
{"id": 45466, "name": "User input_Text", "VB": "Public Sub text()\n    Debug.Print InputBox(\"Input a string\")\n    Debug.Print InputBox(\"Input the integer 75000\", \"Input an integer\", 75000, Context = \"Long\")\nEnd Sub\n", "Java": "import java.util.Scanner;\n\npublic class GetInput {\n    public static void main(String[] args) throws Exception {\n        Scanner s = new Scanner(System.in);\n        System.out.print(\"Enter a string: \");\n        String str = s.nextLine();\n        System.out.print(\"Enter an integer: \");\n        int i = Integer.parseInt(s.next());\n    }\n}\n"}
{"id": 45467, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 45468, "name": "Musical scale", "VB": "Option Explicit\n\nDeclare Function Beep Lib \"kernel32\" (ByVal Freq As Long, ByVal Dur As Long) As Long\n\nSub Musical_Scale()\nDim Fqs, i As Integer\n   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)\n   For i = LBound(Fqs) To UBound(Fqs)\n      Beep Fqs(i), 500\n   Next\nEnd Sub\n", "Java": "\n\nimport processing.sound.*;\n\nfloat[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};\n\nSinOsc sine;\n\nsize(500,500);\n\nsine = new SinOsc(this);\n\nfor(int i=0;i<frequencies.length;i++){\n   sine.freq(frequencies[i]);\n   sine.play();\n\n   delay(500);\n}\n"}
{"id": 45469, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 45470, "name": "Knapsack problem_0-1", "VB": "\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nSub Main()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) / 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        Debug.Print xList(j, 1)\n    Next i\n    Debug.Print \"count=\" & Len(xss), \"weight=\" & xwei, \"value=\" & xval\nEnd Sub \n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub \n", "Java": "package hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n    public ZeroOneKnapsackForTourists() {\n        ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \n\n        \n        zok.add(\"map\", 9, 150);\n        zok.add(\"compass\", 13, 35);\n        zok.add(\"water\", 153, 200);\n        zok.add(\"sandwich\", 50, 160);\n        zok.add(\"glucose\", 15, 60);\n        zok.add(\"tin\", 68, 45);\n        zok.add(\"banana\", 27, 60);\n        zok.add(\"apple\", 39, 40);\n        zok.add(\"cheese\", 23, 30);\n        zok.add(\"beer\", 52, 10);\n        zok.add(\"suntan cream\", 11, 70);\n        zok.add(\"camera\", 32, 30);\n        zok.add(\"t-shirt\", 24, 15);\n        zok.add(\"trousers\", 48, 10);\n        zok.add(\"umbrella\", 73, 40);\n        zok.add(\"waterproof trousers\", 42, 70);\n        zok.add(\"waterproof overclothes\", 43, 75);\n        zok.add(\"note-case\", 22, 80);\n        zok.add(\"sunglasses\", 7, 20);\n        zok.add(\"towel\", 18, 12);\n        zok.add(\"socks\", 4, 50);\n        zok.add(\"book\", 30, 10);\n\n        \n        List<Item> itemList = zok.calcSolution();\n\n        \n        if (zok.isCalculated()) {\n            NumberFormat nf  = NumberFormat.getInstance();\n\n            System.out.println(\n                \"Maximal weight           = \" +\n                nf.format(zok.getMaxWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total weight of solution = \" +\n                nf.format(zok.getSolutionWeight() / 100.0) + \" kg\"\n            );\n            System.out.println(\n                \"Total value              = \" +\n                zok.getProfit()\n            );\n            System.out.println();\n            System.out.println(\n                \"You can carry the following materials \" +\n                \"in the knapsack:\"\n            );\n            for (Item item : itemList) {\n                if (item.getInKnapsack() == 1) {\n                    System.out.format(\n                        \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n                        item.getName(),\n                        item.getWeight(), \"dag  \",\n                        \"(value = \" + item.getValue() + \")\"\n                    );\n                }\n            }\n        } else {\n            System.out.println(\n                \"The problem is not solved. \" +\n                \"Maybe you gave wrong data.\"\n            );\n        }\n\n    }\n\n    public static void main(String[] args) {\n        new ZeroOneKnapsackForTourists();\n    }\n\n} \n"}
{"id": 45471, "name": "Primes - allocate descendants to their ancestors", "VB": "Imports System.Math\n\nModule Module1\n    Const MAXPRIME = 99                             \n    Const MAXPARENT = 99                            \n\n    Const NBRCHILDREN = 547100                      \n\n    Public Primes As New Collection()               \n    Public PrimesR As New Collection()              \n    Public Ancestors As New Collection()            \n\n    Public Parents(MAXPARENT + 1) As Integer        \n    Public CptDescendants(MAXPARENT + 1) As Integer \n    Public Children(NBRCHILDREN) As ChildStruct     \n    Public iChildren As Integer                     \n\n    Public Delimiter As String = \", \"\n    Public Structure ChildStruct\n        Public Child As Long\n        Public pLower As Integer\n        Public pHigher As Integer\n    End Structure\n    Sub Main()\n        Dim Parent As Short\n        Dim Sum As Short\n        Dim i As Short\n        Dim TotDesc As Integer = 0\n        Dim MidPrime As Integer\n\n        If GetPrimes(Primes, MAXPRIME) = vbFalse Then\n            Return\n        End If\n\n        For i = Primes.Count To 1 Step -1\n            PrimesR.Add(Primes.Item(i))\n        Next\n\n        MidPrime = PrimesR.Item(1) / 2\n\n        For Each Prime In PrimesR\n            Parents(Prime) = InsertChild(Parents(Prime), Prime)\n            CptDescendants(Prime) += 1\n\n            If Prime > MidPrime Then\n                Continue For\n            End If\n\n            For Parent = 1 To MAXPARENT\n                Sum = Parent + Prime\n\n                If Sum > MAXPARENT Then\n                    Exit For\n                End If\n\n                If Parents(Parent) Then\n                    InsertPreorder(Parents(Parent), Sum, Prime)\n                    CptDescendants(Sum) += CptDescendants(Parent)\n                End If\n            Next\n        Next\n\n        RemoveFalseChildren()\n\n        If MAXPARENT > MAXPRIME Then\n            If GetPrimes(Primes, MAXPARENT) = vbFalse Then\n                Return\n            End If\n        End If\n\n        FileOpen(1, \"Ancestors.txt\", OpenMode.Output)\n\n        For Parent = 1 To MAXPARENT\n            GetAncestors(Parent)\n            PrintLine(1, \"[\" & Parent.ToString & \"] Level: \" & Ancestors.Count.ToString)\n\n            If Ancestors.Count Then\n                Print(1, \"Ancestors: \" & Ancestors.Item(1).ToString)\n                For i = 2 To Ancestors.Count\n                    Print(1, \", \" & Ancestors.Item(i).ToString)\n                Next\n                PrintLine(1)\n                Ancestors.Clear()\n            Else\n                PrintLine(1, \"Ancestors: None\")\n            End If\n\n            If CptDescendants(Parent) Then\n                PrintLine(1, \"Descendants: \" & CptDescendants(Parent).ToString)\n                Delimiter = \"\"\n                PrintDescendants(Parents(Parent))\n                PrintLine(1)\n                TotDesc += CptDescendants(Parent)\n            Else\n                PrintLine(1, \"Descendants: None\")\n            End If\n\n            PrintLine(1)\n        Next\n        Primes.Clear()\n        PrimesR.Clear()\n        PrintLine(1, \"Total descendants \" & TotDesc.ToString)\n        PrintLine(1)\n        FileClose(1)\n    End Sub\n    Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short)\n        Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime)\n\n        If Children(_index).pLower Then\n            InsertPreorder(Children(_index).pLower, _sum, _prime)\n        End If\n\n        If Children(_index).pHigher Then\n            InsertPreorder(Children(_index).pHigher, _sum, _prime)\n        End If\n\n        Return Nothing\n    End Function\n    Function InsertChild(_index As Integer, _child As Long) As Integer\n        If _index Then\n            If _child <= Children(_index).Child Then\n                Children(_index).pLower = InsertChild(Children(_index).pLower, _child)\n            Else\n                Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child)\n            End If\n        Else\n            iChildren += 1\n            _index = iChildren\n            Children(_index).Child = _child\n            Children(_index).pLower = 0\n            Children(_index).pHigher = 0\n        End If\n\n        Return _index\n    End Function\n    Function RemoveFalseChildren()\n        Dim Exclusions As New Collection\n\n        Exclusions.Add(4)\n        For Each Prime In Primes\n            Exclusions.Add(Prime)\n        Next\n\n        For Each ex In Exclusions\n            Parents(ex) = Children(Parents(ex)).pHigher\n            CptDescendants(ex) -= 1\n        Next\n\n        Exclusions.Clear()\n        Return Nothing\n    End Function\n    Function GetAncestors(_child As Short)\n        Dim Child As Short = _child\n        Dim Parent As Short = 0\n\n        For Each Prime In Primes\n            If Child = 1 Then\n                Exit For\n            End If\n            While Child Mod Prime = 0\n                Child /= Prime\n                Parent += Prime\n            End While\n        Next\n\n        If Parent = _child Or _child = 1 Then\n            Return Nothing\n        End If\n\n        GetAncestors(Parent)\n        Ancestors.Add(Parent)\n        Return Nothing\n    End Function\n    Function PrintDescendants(_index As Integer)\n        If Children(_index).pLower Then\n            PrintDescendants(Children(_index).pLower)\n        End If\n\n        Print(1, Delimiter.ToString & Children(_index).Child.ToString)\n        Delimiter = \", \"\n\n        If Children(_index).pHigher Then\n            PrintDescendants(Children(_index).pHigher)\n        End If\n\n        Return Nothing\n    End Function\n    Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean\n        Dim Value As Integer = 3\n        Dim Max As Integer\n        Dim Prime As Integer\n\n        If _maxPrime < 2 Then\n            Return vbFalse\n        End If\n\n        _primes.Add(2)\n\n        While Value <= _maxPrime\n            Max = Floor(Sqrt(Value))\n\n            For Each Prime In _primes\n                If Prime > Max Then\n                    _primes.Add(Value)\n                    Exit For\n                End If\n\n                If Value Mod Prime = 0 Then\n                    Exit For\n                End If\n            Next\n\n            Value += 2\n        End While\n\n        Return vbTrue\n    End Function\nEnd Module\n", "Java": "import java.io.*;\nimport java.util.*;\n\npublic class PrimeDescendants {\n    public static void main(String[] args) {\n        try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {\n            printPrimeDesc(writer, 100);\n        } catch (IOException ex) {\n            ex.printStackTrace();\n        }\n    }\n\n    private static void printPrimeDesc(Writer writer, int limit) throws IOException {\n        List<Long> primes = findPrimes(limit);\n\n        List<Long> ancestor = new ArrayList<>(limit);\n        List<List<Long>> descendants = new ArrayList<>(limit);\n        for (int i = 0; i < limit; ++i) {\n            ancestor.add(Long.valueOf(0));\n            descendants.add(new ArrayList<Long>());\n        }\n\n        for (Long prime : primes) {\n            int p = prime.intValue();\n            descendants.get(p).add(prime);\n            for (int i = 0; i + p < limit; ++i) {\n                int s = i + p;\n                for (Long n : descendants.get(i)) {\n                    Long prod = n * p;\n                    descendants.get(s).add(prod);\n                    if (prod < limit)\n                        ancestor.set(prod.intValue(), Long.valueOf(s));\n                }\n            }\n        }\n\n        \n        int totalDescendants = 0;\n        for (int i = 1; i < limit; ++i) {\n            List<Long> ancestors = getAncestors(ancestor, i);\n            writer.write(\"[\" + i + \"] Level: \" + ancestors.size() + \"\\n\");\n            writer.write(\"Ancestors: \");\n            Collections.sort(ancestors);\n            print(writer, ancestors);\n\n            writer.write(\"Descendants: \");\n            List<Long> desc = descendants.get(i);\n            if (!desc.isEmpty()) {\n                Collections.sort(desc);\n                if (desc.get(0) == i)\n                    desc.remove(0);\n            }\n            writer.write(desc.size() + \"\\n\");\n            totalDescendants += desc.size();\n            if (!desc.isEmpty())\n                print(writer, desc);\n            writer.write(\"\\n\");\n        }\n        writer.write(\"Total descendants: \" + totalDescendants + \"\\n\");\n    }\n\n    \n    private static List<Long> findPrimes(int limit) {\n        boolean[] isprime = new boolean[limit];\n        Arrays.fill(isprime, true);\n        isprime[0] = isprime[1] = false;\n        for (int p = 2; p * p < limit; ++p) {\n            if (isprime[p]) {\n                for (int i = p * p; i < limit; i += p)\n                    isprime[i] = false;\n            }\n        }\n        List<Long> primes = new ArrayList<>();\n        for (int p = 2; p < limit; ++p) {\n            if (isprime[p])\n                primes.add(Long.valueOf(p));\n        }\n        return primes;\n    }\n\n    \n    private static List<Long> getAncestors(List<Long> ancestor, int n) {\n        List<Long> result = new ArrayList<>();\n        for (Long a = ancestor.get(n); a != 0 && a != n; ) {\n            n = a.intValue();\n            a = ancestor.get(n);\n            result.add(Long.valueOf(n));\n        }\n        return result;\n    }\n\n    private static void print(Writer writer, List<Long> list) throws IOException {\n        if (list.isEmpty()) {\n            writer.write(\"none\\n\");\n            return;\n        }\n        int i = 0;\n        writer.write(String.valueOf(list.get(i++)));\n        for (; i != list.size(); ++i)\n            writer.write(\", \" + list.get(i));\n        writer.write(\"\\n\");\n    }\n}\n"}
{"id": 45472, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 45473, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 45474, "name": "Cartesian product of two or more lists", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n    <Extension()>\n    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))\n        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}\n        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))\n    End Function\n\n    Sub Main()\n        Dim empty(-1) As Integer\n        Dim list1 = {1, 2}\n        Dim list2 = {3, 4}\n        Dim list3 = {1776, 1789}\n        Dim list4 = {7, 12}\n        Dim list5 = {4, 14, 23}\n        Dim list6 = {0, 1}\n        Dim list7 = {1, 2, 3}\n        Dim list8 = {30}\n        Dim list9 = {500, 100}\n\n        For Each sequnceList As Integer()() In {\n            ({list1, list2}),\n            ({list2, list1}),\n            ({list1, empty}),\n            ({empty, list1}),\n            ({list3, list4, list5, list6}),\n            ({list7, list8, list9}),\n            ({list7, empty, list9})\n        }\n            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $\"({String.Join(\", \", tuple)})\")\n            Console.WriteLine($\"{{{String.Join(\", \", cart)}}}\")\n        Next\n    End Sub\n\nEnd Module\n", "Java": "import static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static java.util.Optional.of;\nimport static java.util.stream.Collectors.toList;\n\nimport java.util.List;\n\npublic class CartesianProduct {\n\n    public List<?> product(List<?>... a) {\n        if (a.length >= 2) {\n            List<?> product = a[0];\n            for (int i = 1; i < a.length; i++) {\n                product = product(product, a[i]);\n            }\n            return product;\n        }\n\n        return emptyList();\n    }\n\n    private <A, B> List<?> product(List<A> a, List<B> b) {\n        return of(a.stream()\n                .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))\n                .flatMap(List::stream)\n                .collect(toList())).orElse(emptyList());\n    }\n}\n"}
{"id": 45475, "name": "Proper divisors", "VB": "dim _proper_divisors(100)\n\nsub proper_divisors(n)\n\tdim i\n\tdim _proper_divisors_count = 0\n\tif n <> 1 then\n\t\tfor i = 1 to (n \\ 2)\n\t\t\tif n %% i = 0 then\n\t\t\t\t_proper_divisors_count = _proper_divisors_count + 1\n\t\t\t\t_proper_divisors(_proper_divisors_count) = i \n\t\t\tend if\n\t\tnext\n\tend if\n\treturn _proper_divisors_count\nend sub\n\nsub show_proper_divisors(n, tabbed)\n\tdim cnt = proper_divisors(n)\n\tprint str$(n) + \":\"; tab(4);\"(\" + str$(cnt) + \" items) \";\n\tdim j \n\tfor j = 1 to cnt\n\t\tif tabbed then\n\t\t\tprint str$(_proper_divisors(j)),\n\t\telse \n\t\t\tprint str$(_proper_divisors(j));\n\t\tend if\n\t\tif (j < cnt) then print \",\";\n\tnext\n\tprint\nend sub\n\ndim i\nfor i = 1 to 10\n    show_proper_divisors(i, false)\nnext\n\ndim c \ndim maxindex = 0\ndim maxlength = 0\nfor t = 1 to 20000\n\tc = proper_divisors(t)\n\tif c > maxlength then\n\t\tmaxindex = t\n\t\tmaxlength = c\n\tend if\nnext\n\nprint \"A maximum at \";\nshow_proper_divisors(maxindex, false)\n", "Java": "import java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Proper{\n    public static List<Integer> properDivs(int n){\n        List<Integer> divs = new LinkedList<Integer>();\n        if(n == 1) return divs;\n        divs.add(1);\n        for(int x = 2; x < n; x++){\n            if(n % x == 0) divs.add(x);\n        }\n        \n        Collections.sort(divs);\n        \n        return divs;\n    }\n    \n    public static void main(String[] args){\n        for(int x = 1; x <= 10; x++){\n            System.out.println(x + \": \" + properDivs(x));\n        }\n        \n        int x = 0, count = 0;\n        for(int n = 1; n <= 20000; n++){\n            if(properDivs(n).size() > count){\n                x = n;\n                count = properDivs(n).size();\n            }\n        }\n        System.out.println(x + \": \" + count);\n    }\n}\n"}
{"id": 45476, "name": "XML_Output", "VB": "Module XMLOutput\n    Sub Main()\n        Dim charRemarks As New Dictionary(Of String, String)\n        charRemarks.Add(\"April\", \"Bubbly: I\n        charRemarks.Add(\"Tam O\n        charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n        Dim xml = <CharacterRemarks>\n                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n                  </CharacterRemarks>\n\n        Console.WriteLine(xml)\n    End Sub\nEnd Module\n", "Java": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n  private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n  private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n    \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n      \"Short & shrift\"};\n  \n  public static void main(String[] args) {\n    try {\n      \n      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n      \n      \n      final Element root = doc.createElement(\"CharacterRemarks\");\n      doc.appendChild(root);\n      \n      \n      for(int i = 0; i < names.length; i++) {\n        final Element character = doc.createElement(\"Character\");\n        root.appendChild(character);\n        character.setAttribute(\"name\", names[i]);\n        character.appendChild(doc.createTextNode(remarks[i]));\n      }\n      \n      \n      \n      final Source source = new DOMSource(doc);\n      \n      \n      final StringWriter buffer = new StringWriter();\n      \n      \n      final Result result = new StreamResult(buffer);\n      \n      \n      final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n      transformer.setOutputProperty(\"indent\", \"yes\");\n      transformer.transform(source, result);\n      \n      \n      \n      System.out.println(buffer.toString());\n    } catch (Exception e) {\n      e.printStackTrace();\n    }\n  }\n  \n}\n"}
{"id": 45477, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 45478, "name": "Plot coordinate pairs", "VB": "Private Sub plot_coordinate_pairs(x As Variant, y As Variant)\n    Dim chrt As Chart\n    Set chrt = ActiveSheet.Shapes.AddChart.Chart\n    With chrt\n        .ChartType = xlLine\n        .HasLegend = False\n        .HasTitle = True\n        .ChartTitle.Text = \"Time\"\n        .SeriesCollection.NewSeries\n        .SeriesCollection.Item(1).XValues = x\n        .SeriesCollection.Item(1).Values = y\n        .Axes(xlValue, xlPrimary).HasTitle = True\n        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = \"microseconds\"\n    End With\nEnd Sub\nPublic Sub main()\n    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]\n    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]\n    plot_coordinate_pairs x, y\nEnd Sub\n", "Java": "  import java.awt.*;\n  import java.awt.event.*;\n  import java.awt.geom.*;\n  import javax.swing.JApplet;\n  import javax.swing.JFrame;\n  public class Plot2d extends JApplet {\n    double[] xi;\n    double[] yi;\n    public Plot2d(double[] x, double[] y) {\n        this.xi = x;\n        this.yi = y;\n    }\n    public static double max(double[] t) {\n        double maximum = t[0];   \n        for (int i = 1; i < t.length; i++) {\n            if (t[i] > maximum) {\n                maximum = t[i];  \n            }\n        }\n        return maximum;\n    }\n    public static double min(double[] t) {\n        double minimum = t[0];\n        for (int i = 1; i < t.length; i++) {\n            if (t[i] < minimum) {\n                minimum = t[i];\n            }\n        }\n        return minimum;\n    }\n    public void init() {\n        setBackground(Color.white);\n        setForeground(Color.white);\n    }\n    public void paint(Graphics g) {\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                RenderingHints.VALUE_ANTIALIAS_ON);\n        g2.setPaint(Color.black);\n        int x0 = 70;\n        int y0 = 10;\n        int xm = 670;\n        int ym = 410;\n        int xspan = xm - x0;\n        int yspan = ym - y0;\n        double xmax = max(xi);\n        double xmin = min(xi);\n        double ymax = max(yi);\n        double ymin = min(yi);\n        g2.draw(new Line2D.Double(x0, ym, xm, ym));\n        g2.draw(new Line2D.Double(x0, ym, x0, y0));\n        for (int j = 0; j < 5; j++) {\n            int interv = 4;\n            g2.drawString(\"\" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);\n            g2.drawString(\"\" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),\n ym - j * yspan / interv + y0 - 5);\n            g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));\n            g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));\n        }\n        for (int i = 0; i < xi.length; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            g2.drawString(\"o\", x0 + f - 3, h + 14);\n        }\n        for (int i = 0; i < xi.length - 1; i++) {\n            int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));\n            int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));\n            int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));\n            int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));\n            g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));\n        }\n    }\n    public static void main(String args[]) {\n        JFrame f = new JFrame(\"ShapesDemo2D\");\n        f.addWindowListener(new WindowAdapter() {\n            public void windowClosing(WindowEvent e) {\n                System.exit(0);\n            }\n        });\n        double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};\n        JApplet applet = new Plot2d(r, t);\n        f.getContentPane().add(\"Center\", applet);\n        applet.init();\n        f.pack();\n        f.setSize(new Dimension(720, 480));\n        f.show();\n    }\n  }\n"}
{"id": 45479, "name": "Regular expressions", "VB": "text = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n", "Java": "String str = \"I am a string\";\nif (str.matches(\".*string\")) { \n  System.out.println(\"ends with 'string'\");\n}\n"}
{"id": 45480, "name": "Hash from two arrays", "VB": "Set dict = CreateObject(\"Scripting.Dictionary\")\nos = Array(\"Windows\", \"Linux\", \"MacOS\")\nowner = Array(\"Microsoft\", \"Linus Torvalds\", \"Apple\")\nFor n = 0 To 2\n    dict.Add os(n), owner(n)\nNext\nMsgBox dict.Item(\"Linux\")\nMsgBox dict.Item(\"MacOS\")\nMsgBox dict.Item(\"Windows\")\n", "Java": "import java.util.HashMap;\npublic static void main(String[] args){\n\tString[] keys= {\"a\", \"b\", \"c\"};\n\tint[] vals= {1, 2, 3};\n\tHashMap<String, Integer> hash= new HashMap<String, Integer>();\n\n\tfor(int i= 0; i < keys.length; i++){\n\t   hash.put(keys[i], vals[i]);\n\t}\n}\n"}
{"id": 45481, "name": "Colour pinstripe_Display", "VB": "Public Class Main\n    Inherits System.Windows.Forms.Form\n    Public Sub New()\n        Me.FormBorderStyle = FormBorderStyle.None\n        Me.WindowState = FormWindowState.Maximized\n    End Sub\n    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load\n        Dim Index As Integer\n        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}\n        Dim Height = (Me.ClientSize.Height / 4) + 1\n        For y = 1 To 4\n            Dim Top = Me.ClientSize.Height / 4 * (y - 1)\n            For x = 0 To Me.ClientSize.Width Step y\n                If Index = 6 Then Index = 0 Else Index += 1\n                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})\n            Next\n        Next\n    End Sub\nEnd Class\n", "Java": "import java.awt.*;\nimport static java.awt.Color.*;\nimport javax.swing.*;\n\npublic class ColourPinstripeDisplay extends JPanel {\n    final static Color[] palette = {black, red, green, blue, magenta,cyan,\n        yellow, white};\n\n    final int bands = 4;\n\n    public ColourPinstripeDisplay() {\n        setPreferredSize(new Dimension(900, 600));\n    }\n\n    @Override\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n        int h = getHeight();\n        for (int b = 1; b <= bands; b++) {\n            for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {\n                g.setColor(palette[colIndex % palette.length]);\n                g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        SwingUtilities.invokeLater(() -> {\n            JFrame f = new JFrame();\n            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            f.setTitle(\"ColourPinstripeDisplay\");\n            f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);\n            f.pack();\n            f.setLocationRelativeTo(null);\n            f.setVisible(true);\n        });\n    }\n}\n"}
{"id": 45482, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "VB": "\n\nFunction cocktailShakerSort(ByVal A As Variant) As Variant\n    beginIdx = LBound(A)\n    endIdx = UBound(A) - 1\n    Do While beginIdx <= endIdx\n        newBeginIdx = endIdx\n        newEndIdx = beginIdx\n        For ii = beginIdx To endIdx\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newEndIdx = ii\n            End If\n        Next ii\n        endIdx = newEndIdx - 1\n        For ii = endIdx To beginIdx Step -1\n            If A(ii) > A(ii + 1) Then\n                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp\n                newBeginIdx = ii\n            End If\n        Next ii\n        beginIdx = newBeginIdx + 1\n    Loop\n    cocktailShakerSort = A\nEnd Function \n\nPublic Sub main()\n    Dim B(20) As Variant\n    For i = LBound(B) To UBound(B)\n        B(i) = Int(Rnd() * 100)\n    Next i\n    Debug.Print Join(B, \", \")\n    Debug.Print Join(cocktailShakerSort(B), \", \")\nEnd Sub\n", "Java": "import java.util.*;\n\npublic class CocktailSort {\n    public static void main(String[] args) {\n        Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };\n        System.out.println(\"before: \" + Arrays.toString(array));\n        cocktailSort(array);\n        System.out.println(\"after: \" + Arrays.toString(array));\n    }\n\n    \n    public static void cocktailSort(Object[] array) {\n        int begin = 0;\n        int end = array.length;\n        if (end == 0)\n            return;\n        for (--end; begin < end; ) {\n            int new_begin = end;\n            int new_end = begin;\n            for (int i = begin; i < end; ++i) {\n                Comparable c1 = (Comparable)array[i];\n                Comparable c2 = (Comparable)array[i + 1];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i + 1);\n                    new_end = i;\n                }\n            }\n            end = new_end;\n            for (int i = end; i > begin; --i) {\n                Comparable c1 = (Comparable)array[i - 1];\n                Comparable c2 = (Comparable)array[i];\n                if (c1.compareTo(c2) > 0) {\n                    swap(array, i, i - 1);\n                    new_begin = i;\n                }\n            }\n            begin = new_begin;\n        }\n    }\n\n    private static void swap(Object[] array, int i, int j) {\n        Object tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n}\n"}
{"id": 45483, "name": "Animate a pendulum", "VB": "option explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  \n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x<xf Then sx=+1: Else sx=-1\n  If y<yf Then sy=+1: Else sy=-1\n  err=dx-dy\n  Do\n    toxy x,y,\".\"\n    If x=xf And y=yf Then Exit Do\n    err2=err+err\n    If err2>-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n", "Java": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n    private double angle = Math.PI / 2;\n    private int length;\n\n    public Pendulum(int length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    public void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;\n        int ballX = anchorX + (int) (Math.sin(angle) * length);\n        int ballY = anchorY + (int) (Math.cos(angle) * length);\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    public void run() {\n        double angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 / length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    public Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, length / 2 * 3);\n    }\n\n    public static void main(String[] args) {\n        JFrame f = new JFrame(\"Pendulum\");\n        Pendulum p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n"}
{"id": 45484, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 45485, "name": "Gray code", "VB": "Function Encoder(ByVal n)\n    Encoder = n Xor (n \\ 2)\nEnd Function\n\nFunction Decoder(ByVal n)\n    Dim g : g = 0\n    Do While n > 0\n       g = g Xor n\n       n = n \\ 2\n    Loop\n    Decoder = g\nEnd Function\n\n\nFunction Dec2bin(ByVal n, ByVal length)\n    Dim i, strbin : strbin = \"\"\n    For i = 1 to 5\n        strbin = (n Mod 2) & strbin\n        n = n \\ 2\n    Next\n    Dec2Bin = strbin\nEnd Function\n\nWScript.StdOut.WriteLine(\"Binary -> Gray Code -> Binary\")\nFor i = 0 to 31\n    encoded = Encoder(i)\n    decoded = Decoder(encoded)\n    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & \" -> \" & Dec2Bin(encoded, 5) & \" -> \" & Dec2Bin(decoded, 5))\nNext\n", "Java": "public class Gray {\n\tpublic static long grayEncode(long n){\n\t\treturn n ^ (n >>> 1);\n\t}\n\t\n\tpublic static long grayDecode(long n) {\n\t\tlong p = n;\n\t\twhile ((n >>>= 1) != 0)\n\t\t\tp ^= n;\n\t\treturn p;\n\t}\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(\"i\\tBinary\\tGray\\tDecoded\");\n\t\tfor(int i = -1; i < 32;i++){\n\t\t\tSystem.out.print(i +\"\\t\");\n\t\t\tSystem.out.print(Integer.toBinaryString(i) + \"\\t\");\n\t\t\tSystem.out.print(Long.toBinaryString(grayEncode(i))+ \"\\t\");\n\t\t\tSystem.out.println(grayDecode(grayEncode(i)));\n\t\t}\n\t}\n}\n"}
{"id": 45486, "name": "Playing cards", "VB": "class playingcard\n\tdim suit\n\tdim pips\nend class\n\nclass carddeck\n\tprivate suitnames\n\tprivate pipnames\n\tprivate cardno\n\tprivate deck(52)\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tdim suit\n\t\tdim pips\n\t\tsuitnames = split(\"H,D,C,S\",\",\")\n\t\tpipnames = split(\"A,2,3,4,5,6,7,8,9,10,J,Q,K\",\",\")\n\t\tcardno = 0\n\n\t\tfor suit = 1 to 4\n\t\t\tfor pips = 1 to 13\n\t\t\t\tset deck(cardno) = new playingcard\n\t\t\t\tdeck(cardno).suit = suitnames(suit-1)\n\t\t\t\tdeck(cardno).pips = pipnames(pips-1)\n\t\t\t\tcardno = cardno + 1\n\t\t\tnext\n\t\tnext\n\t\tnTop = 0\n\tend sub\n\t\n\tpublic sub showdeck\n\t\tdim a\n\t\tredim a(51-nTop)\n\t\tfor i = nTop to 51\n\t\t\ta(i) = deck(i).pips & deck(i).suit  \n\t\tnext\n\t\twscript.echo join( a, \", \")\n\tend sub\n\t\n\tpublic sub shuffle\n\t\tdim r\n\t\trandomize timer\n\t\tfor i = nTop to 51\n\t\t\tr = int( rnd * ( 52 - nTop ) ) \n\t\t\tif r <> i then\n\t\t\t\tobjswap deck(i),deck(r)\n\t\t\tend if\n\t\tnext\n\tend sub\n\n\tpublic function deal()\n\t\tset deal = deck( nTop )\n\t\tnTop = nTop + 1\n\tend function\n\n\tpublic property get cardsRemaining\n\t\tcardsRemaining = 52 - nTop\n\tend property\n\t\n\tprivate sub objswap(   a,   b )\n\t\tdim tmp\n\t\tset tmp = a\n\t\tset a = b\n\t\tset b = tmp\n\tend sub\nend class\n", "Java": "public enum Pip { Two, Three, Four, Five, Six, Seven, \n    Eight, Nine, Ten, Jack, Queen, King, Ace }\n"}
{"id": 45487, "name": "Arrays", "VB": "Option Base {0|1}\n", "Java": "Int[] literalArray = [1,2,3];\nInt[] fixedLengthArray = new Int[10];\nInt[] variableArray = new Int[];\n\nassert literalArray.size == 3; \nInt n = literalArray[2];       \nfixedLengthArray[4] = 12345;   \n\nfixedLengthArray += 6789;  \nvariableArray    += 6789;  \n"}
{"id": 45488, "name": "Sierpinski carpet", "VB": "Const Order = 4\n\nFunction InCarpet(ByVal x As Integer, ByVal y As Integer)\n    Do While x <> 0 And y <> 0\n        If x Mod 3 = 1 And y Mod 3 = 1 Then\n            InCarpet = \" \"\n            Exit Function\n        End If\n        x = x \\ 3\n        y = y \\ 3\n    Loop\n    InCarpet = \"#\"\nEnd Function\n \nPublic Sub sierpinski_carpet()\n    Dim i As Integer, j As Integer\n    For i = 0 To 3 ^ Order - 1\n        For j = 0 To 3 ^ Order - 1\n            Debug.Print InCarpet(i, j);\n        Next j\n        Debug.Print\n    Next i\nEnd Sub\n", "Java": "public static boolean inCarpet(long x, long y) {\n    while (x!=0 && y!=0) {\n        if (x % 3 == 1 && y % 3 == 1)\n            return false;\n        x /= 3;\n        y /= 3;\n    }\n    return true;\n}\n \npublic static void carpet(final int n) {\n    final double power = Math.pow(3,n);\n    for(long i = 0; i < power; i++) {\n        for(long j = 0; j < power; j++) {\n            System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n        }\n        System.out.println();\n    }\n}\n"}
{"id": 45489, "name": "Sorting algorithms_Bogosort", "VB": "Private Function Knuth(a As Variant) As Variant\n    Dim t As Variant, i As Integer\n    If Not IsMissing(a) Then\n        For i = UBound(a) To LBound(a) + 1 Step -1\n            j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))\n            t = a(i)\n            a(i) = a(j)\n            a(j) = t\n        Next i\n    End If\n    Knuth = a\nEnd Function\n\nPrivate Function inOrder(s As Variant)\n    i = 2\n    Do While i <= UBound(s)\n         If s(i) < s(i - 1) Then\n            inOrder = False\n            Exit Function\n        End If\n        i = i + 1\n    Loop\n    inOrder = True\nEnd Function\n \nPrivate Function bogosort(ByVal s As Variant) As Variant\n    Do While Not inOrder(s)\n        Debug.Print Join(s, \", \")\n        s = Knuth(s)\n    Loop\n    bogosort = s\nEnd Function\n \nPublic Sub main()\n    Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), \", \")\nEnd Sub\n", "Java": "public class BogoSort \n{\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tint[] arr={4,5,6,0,7,8,9,1,2,3};\n\t\t\n\t\tBogoSort now=new BogoSort();\n\t\tSystem.out.print(\"Unsorted: \");\n\t\tnow.display1D(arr);\n\t\t\n\t\tnow.bogo(arr);\n\t\t\n\t\tSystem.out.print(\"Sorted: \");\n\t\tnow.display1D(arr);\n\t}\n\tvoid bogo(int[] arr)\n\t{\n\t\t\n\t\tint shuffle=1;\n\t\tfor(;!isSorted(arr);shuffle++)\n\t\t\tshuffle(arr);\n\t\t\n\t\tSystem.out.println(\"This took \"+shuffle+\" shuffles.\");\n\t}\n\tvoid shuffle(int[] arr)\n\t{\n\t\t\n\t\tint i=arr.length-1;\n\t\twhile(i>0)\n\t\t\tswap(arr,i--,(int)(Math.random()*i));\n\t}\n\tvoid swap(int[] arr,int i,int j)\n\t{\n\t\tint temp=arr[i];\n\t\tarr[i]=arr[j];\n\t\tarr[j]=temp;\n\t}\n\tboolean isSorted(int[] arr)\n\t{\n\n\t\tfor(int i=1;i<arr.length;i++)\n\t\t\tif(arr[i]<arr[i-1])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvoid display1D(int[] arr)\n\t{\n\t\tfor(int i=0;i<arr.length;i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\n}\n"}
{"id": 45490, "name": "Euler method", "VB": "Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)\n    Dim t As Integer\n    Debug.Print \" Step \"; step; \": \",\n    Do While t <= end_t\n        If t Mod 10 = 0 Then Debug.Print Format(y, \"0.000\"),\n        y = y + step * Application.Run(f, y)\n        t = t + step\n    Loop\n    Debug.Print\nEnd Sub\n \nSub analytic()\n    Debug.Print \"    Time: \",\n    For t = 0 To 100 Step 10\n        Debug.Print \" \"; t,\n    Next t\n    Debug.Print\n    Debug.Print \"Analytic: \",\n    For t = 0 To 100 Step 10\n        Debug.Print Format(20 + 80 * Exp(-0.07 * t), \"0.000\"),\n    Next t\n    Debug.Print\nEnd Sub\n \nPrivate Function cooling(temp As Double) As Double\n    cooling = -0.07 * (temp - 20)\nEnd Function\n\nPublic Sub euler_method()\n    Dim r_cooling As String\n    r_cooling = \"cooling\"\n    analytic\n    ivp_euler r_cooling, 100, 2, 100\n    ivp_euler r_cooling, 100, 5, 100\n    ivp_euler r_cooling, 100, 10, 100\nEnd Sub\n", "Java": "public class Euler {\n  private static void euler (Callable f, double y0, int a, int b, int h) {\n    int t = a;\n    double y = y0;\n    while (t < b) {\n      System.out.println (\"\" + t + \" \" + y);\n      t += h;\n      y += h * f.compute (t, y);\n    }\n    System.out.println (\"DONE\");\n  }\n\n  public static void main (String[] args) {\n    Callable cooling = new Cooling ();\n    int[] steps = {2, 5, 10};\n    for (int stepSize : steps) {\n      System.out.println (\"Step size: \" + stepSize);\n      euler (cooling, 100.0, 0, 100, stepSize);\n    }\n  }\n}\n\n\ninterface Callable {\n  public double compute (int time, double t);\n}\n\n\nclass Cooling implements Callable {\n  public double compute (int time, double t) {\n    return -0.07 * (t - 20);\n  }\n}\n"}
{"id": 45491, "name": "Sequence of non-squares", "VB": "Sub Main()\nDim i&, c&, j#, s$\nConst N& = 1000000\n   s = \"values for n in the range 1 to 22 : \"\n   For i = 1 To 22\n      s = s & ns(i) & \", \"\n   Next\n   For i = 1 To N\n      j = Sqr(ns(i))\n      If j = CInt(j) Then c = c + 1\n   Next\n   \n   Debug.Print s\n   Debug.Print c & \" squares less than \" & N\nEnd Sub\n\nPrivate Function ns(l As Long) As Long\n   ns = l + Int(1 / 2 + Sqr(l))\nEnd Function\n", "Java": "public class SeqNonSquares {\n    public static int nonsqr(int n) {\n        return n + (int)Math.round(Math.sqrt(n));\n    }\n    \n    public static void main(String[] args) {\n        \n        for (int i = 1; i < 23; i++)\n            System.out.print(nonsqr(i) + \" \");\n        System.out.println();\n        \n        \n        for (int i = 1; i < 1000000; i++) {\n            double j = Math.sqrt(nonsqr(i));\n            assert j != Math.floor(j);\n        }\n    }\n}\n"}
{"id": 45492, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 45493, "name": "Substring", "VB": "Public Sub substring()\n\n\n\n\n\n \n    sentence = \"the last thing the man said was the\"\n    n = 10: m = 5\n       \n    \n    Debug.Print Mid(sentence, n, 5)\n    \n    Debug.Print Right(sentence, Len(sentence) - n + 1)\n    \n    Debug.Print Left(sentence, Len(sentence) - 1)\n    \n    k = InStr(1, sentence, \"m\")\n    Debug.Print Mid(sentence, k, 5)\n    \n    k = InStr(1, sentence, \"aid\")\n    Debug.Print Mid(sentence, k, 5)\nEnd Sub\n", "Java": "public static String Substring(String str, int n, int m){\n    return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n    return str.substring(n);\n}\npublic static String Substring(String str){\n    return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n"}
{"id": 45494, "name": "JortSort", "VB": "Function JortSort(s)\n\tJortSort = True\n\tarrPreSort = Split(s,\",\")\n\tSet arrSorted = CreateObject(\"System.Collections.ArrayList\")\n\t\n\tFor i = 0 To UBound(arrPreSort)\n\t\tarrSorted.Add(arrPreSort(i))\n\tNext\n\tarrSorted.Sort()\n\t\n\tFor j = 0 To UBound(arrPreSort)\n\t\tIf arrPreSort(j) <> arrSorted(j) Then\n\t\t\tJortSort = False\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write JortSort(\"1,2,3,4,5\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"1,2,3,5,4\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,b,c\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write JortSort(\"a,c,b\")\n", "Java": "public class JortSort {\n    public static void main(String[] args) {\n        System.out.println(jortSort(new int[]{1, 2, 3}));\n    }\n\n    static boolean jortSort(int[] arr) {\n        return true;\n    }\n}\n"}
{"id": 45495, "name": "Leap year", "VB": "Public Function Leap_year(year As Integer) As Boolean\n    Leap_year = (Month(DateSerial(year, 2, 29)) = 2)\nEnd Function\n", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n        public static void main(String[] argv){\n                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n                GregorianCalendar cal = new GregorianCalendar();\n                for(int year : yrs){\n                        System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n                                                                 year, cal.isLeapYear(year), isLeapYear(year)));\n                }\n\n        }\n        public static boolean isLeapYear(int year){\n                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n        }\n}\n"}
{"id": 45496, "name": "Combinations and permutations", "VB": "\ndim i,j\nWscript.StdOut.WriteLine  \"-- Long Integer - Permutations - from 1 to 12\"\nfor i=1 to 12\n\tfor j=1 to i\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 10 to 60\"\nfor i=10 to 60 step 10\n\tfor j=1 to i step i\\5\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Permutations from 5000 to 15000\"\nfor i=5000 to 15000 step 5000\n\tfor j=10 to 70 step 20\n\t\tWscript.StdOut.Write  \"C(\" & i & \",\" & j & \")=\" & perm(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \nWscript.StdOut.WriteLine  \"-- Float integer - Combinations from 200 to 1000\"\nfor i=200 to 1000 step 200\n\tfor j=20 to 100 step 20\n\t\tWscript.StdOut.Write \"P(\" & i & \",\" & j & \")=\" & comb(i,j) & \"  \"\n\tnext \n\tWscript.StdOut.WriteLine \"\"\nnext \n\nfunction perm(x,y)\n\tdim i,z\n\tz=1\n\tfor i=x-y+1 to x\n\t\tz=z*i\n\tnext \n\tperm=z\nend function \n\t\nfunction fact(x)\n\tdim i,z\n\tz=1\n\tfor i=2 to x\n\t\tz=z*i\n\tnext \n\tfact=z\nend function \n\nfunction comb(byval x,byval y)\n\tif y>x then \n\t\tcomb=0\n\telseif x=y then \n\t\tcomb=1\n\telse\n\t\tif x-y<y then y=x-y\n\t\tcomb=perm(x,y)/fact(y)\n\tend if\nend function \n", "Java": "import java.math.BigInteger;\n\npublic class CombinationsAndPermutations {\n\n    public static void main(String[] args) {\n        System.out.println(Double.MAX_VALUE);\n        System.out.println(\"A sample of permutations from 1 to 12 with exact Integer arithmetic:\");\n        for ( int n = 1 ; n <= 12 ; n++ ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, permutation(n, k));\n        }\n\n        System.out.println();\n        System.out.println(\"A sample of combinations from 10 to 60 with exact Integer arithmetic:\");\n        for ( int n = 10 ; n <= 60 ; n += 5 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, combination(n, k));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of permutations from 5 to 15000 displayed in floating point arithmetic:\");\n        System.out.printf(\"%d P %d = %s%n\", 5, 2, display(permutation(5, 2), 50));\n        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {\n            int k = n / 2;\n            System.out.printf(\"%d P %d = %s%n\", n, k, display(permutation(n, k), 50));\n        }\n        \n        System.out.println();\n        System.out.println(\"A sample of combinations from 100 to 1000 displayed in floating point arithmetic:\");\n        for ( int n = 100 ; n <= 1000 ; n += 100 ) {\n            int k = n / 2;\n            System.out.printf(\"%d C %d = %s%n\", n, k, display(combination(n, k), 50));\n        }\n\n    }\n    \n    private static String display(BigInteger val, int precision) {\n        String s = val.toString();\n        precision = Math.min(precision, s.length());\n        StringBuilder sb = new StringBuilder();\n        sb.append(s.substring(0, 1));\n        sb.append(\".\");\n        sb.append(s.substring(1, precision));\n        sb.append(\" * 10^\");\n        sb.append(s.length()-1);\n        return sb.toString();\n    }\n    \n    public static BigInteger combination(int n, int k) {\n        \n        \n        if ( n-k < k ) {\n            k = n-k;\n        }\n        BigInteger result = permutation(n, k);\n        while ( k > 0 ) {\n            result = result.divide(BigInteger.valueOf(k));\n            k--;\n        }\n        return result;\n    }\n    \n    public static BigInteger permutation(int n, int k) {\n        BigInteger result = BigInteger.ONE;\n        for ( int i = n ; i >= n-k+1 ; i-- ) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n    \n}\n"}
{"id": 45497, "name": "Sort numbers lexicographically", "VB": "Public Function sortlexicographically(N As Integer)\n    Dim arrList As Object\n    Set arrList = CreateObject(\"System.Collections.ArrayList\")\n    For i = 1 To N\n        arrList.Add CStr(i)\n    Next i\n    arrList.Sort\n    Dim item As Variant\n    For Each item In arrList\n        Debug.Print item & \", \";\n    Next\nEnd Function\n\nPublic Sub main()\n    Call sortlexicographically(13)\nEnd Sub\n", "Java": "import java.util.List;\nimport java.util.stream.*;\n\npublic class LexicographicalNumbers {\n\n    static List<Integer> lexOrder(int n) {\n        int first = 1, last = n;\n        if (n < 1) {\n            first = n;\n            last = 1;\n        }\n        return IntStream.rangeClosed(first, last)\n                        .mapToObj(Integer::toString)\n                        .sorted()\n                        .map(Integer::valueOf)\n                        .collect(Collectors.toList());\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"In lexicographical order:\\n\");\n        int[] ints = {0, 5, 13, 21, -22};\n        for (int n : ints) {\n           System.out.printf(\"%3d: %s\\n\", n, lexOrder(n));\n        }\n    }\n}\n"}
{"id": 45498, "name": "Number names", "VB": "Public twenties As Variant\nPublic decades As Variant\nPublic orders As Variant\n\nPrivate Sub init()\n    twenties = [{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"}]\n    decades = [{\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}]\n    orders = [{1E15,\"quadrillion\"; 1E12,\"trillion\"; 1E9,\"billion\"; 1E6,\"million\"; 1E3,\"thousand\"}]\nEnd Sub\n\nPrivate Function Twenty(N As Variant)\n    Twenty = twenties(N Mod 20 + 1)\nEnd Function\n \nPrivate Function Decade(N As Variant)\n    Decade = decades(N Mod 10 - 1)\nEnd Function\n \nPrivate Function Hundred(N As Variant)\n    If N < 20 Then\n        Hundred = Twenty(N)\n        Exit Function\n    Else\n        If N Mod 10 = 0 Then\n            Hundred = Decade((N \\ 10) Mod 10)\n            Exit Function\n        End If\n    End If\n    Hundred = Decade(N \\ 10) & \"-\" & Twenty(N Mod 10)\nEnd Function\n \nPrivate Function Thousand(N As Variant, withand As String)\n    If N < 100 Then\n        Thousand = withand & Hundred(N)\n        Exit Function\n    Else\n        If N Mod 100 = 0 Then\n            Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & \" hundred\"\n            Exit Function\n        End If\n    End If\n    Thousand = Twenty(N \\ 100) & \" hundred and \" & Hundred(N Mod 100)\nEnd Function\n\nPrivate Function Triplet(N As Variant)\n    Dim Order, High As Variant, Low As Variant\n    Dim Name As String, res As String\n    For i = 1 To UBound(orders)\n        Order = orders(i, 1)\n        Name = orders(i, 2)\n        High = WorksheetFunction.Floor_Precise(N / Order)\n        Low = N - High * Order \n        If High <> 0 Then\n            res = res & Thousand(High, \"\") & \" \" & Name\n        End If\n        N = Low\n        If Low = 0 Then Exit For\n        If Len(res) And High <> 0 Then\n            res = res & \", \"\n        End If\n    Next i\n    If N <> 0 Or res = \"\" Then\n        res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = \"\", \"\", \"and \"))\n        N = N - Int(N)\n        If N > 0.000001 Then\n            res = res & \" point\"\n            For i = 1 To 10\n                n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)\n                res = res & \" \" & twenties(n_ + 1)\n                N = N * 10 - n_\n                If Abs(N) < 0.000001 Then Exit For\n            Next i\n        End If\n    End If\n    Triplet = res\nEnd Function\n \nPrivate Function spell(N As Variant)\n    Dim res As String\n    If N < 0 Then\n        res = \"minus \"\n        N = -N\n    End If\n    res = res & Triplet(N)\n    spell = res\nEnd Function\n \nPrivate Function smartp(N As Variant)\n    Dim res As String\n    If N = WorksheetFunction.Floor_Precise(N) Then\n        smartp = CStr(N)\n        Exit Function\n    End If\n    res = CStr(N)\n    If InStr(1, res, \".\") Then\n        res = Left(res, InStr(1, res, \".\"))\n    End If\n    smartp = res\nEnd Function\n \nSub Main()\n    Dim si As Variant\n    init\n    Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]\n    Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]\n    For i = 1 To UBound(Samples1)\n        si = Samples1(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\n    For i = 1 To UBound(Samples2)\n        si = Samples2(i)\n        Debug.Print Format(smartp(si), \"@@@@@@@@@@@@@@@@\"); \" \"; spell(si)\n    Next i\nEnd Sub\n", "Java": "module NumberNames\n    {\n    void run()\n        {\n        @Inject Console console;\n\n        Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,\n                       123456789000, 0x123456789ABCDEF];\n        for (Int test : tests)\n            {\n            console.print($\"{test} = {toEnglish(test)}\");\n            }\n        }\n\n    static String[] digits = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n                              \"five\", \"six\", \"seven\", \"eight\", \"nine\"];\n    static String[] teens  = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n                              \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"];\n    static String[] tens   = [\"zero\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n                              \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"];\n    static String[] ten3rd = [\"?\", \"thousand\", \"million\", \"billion\", \"trillion\",\n                              \"quadrillion\", \"quintillion\"];\n\n    static String toEnglish(Int n)\n        {\n        StringBuffer buf = new StringBuffer();\n        if (n < 0)\n            {\n            \"negative \".appendTo(buf);\n            n = -n;\n            }\n\n        format3digits(n, buf);\n        return buf.toString();\n        }\n\n    static void format3digits(Int n, StringBuffer buf, Int nested=0)\n        {\n        (Int left, Int right) = n /% 1000;\n        if (left != 0)\n            {\n            format3digits(left, buf, nested+1);\n            }\n\n        if (right != 0 || (left == 0 && nested==0))\n            {\n            if (right >= 100)\n                {\n                (left, right) = (right /% 100);\n                digits[left].appendTo(buf);\n                \" hundred \".appendTo(buf);\n                if (right != 0)\n                    {\n                    format2digits(right, buf);\n                    }\n                }\n            else\n                {\n                format2digits(right, buf);\n                }\n\n            if (nested > 0)\n                {\n                ten3rd[nested].appendTo(buf).add(' ');\n                }\n            }\n        }\n\n    static void format2digits(Int n, StringBuffer buf)\n        {\n        switch (n)\n            {\n            case 0..9:\n                digits[n].appendTo(buf).add(' ');\n                break;\n\n            case 10..19:\n                teens[n-10].appendTo(buf).add(' ');\n                break;\n\n            default:\n                (Int left, Int right) = n /% 10;\n                tens[left].appendTo(buf);\n                if (right == 0)\n                    {\n                    buf.add(' ');\n                    }\n                else\n                    {\n                    buf.add('-');\n                    digits[right].appendTo(buf).add(' ');\n                    }\n                break;\n            }\n        }\n    }\n"}
{"id": 45499, "name": "Sorting algorithms_Shell sort", "VB": "Sub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  \n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub\n", "Java": "public static void shell(int[] a) {\n\tint increment = a.length / 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 / 11);\n\t\t}\n\t}\n}\n"}
{"id": 45500, "name": "Doubly-linked list_Definition", "VB": "Public Class DoubleLinkList(Of T)\n   Private m_Head As Node(Of T)\n   Private m_Tail As Node(Of T)\n\n   Public Sub AddHead(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Head Is Nothing Then\n           m_Head = Node\n           m_Tail = m_Head\n       Else\n           node.Next = m_Head\n           m_Head = node\n       End If\n\n   End Sub\n\n   Public Sub AddTail(ByVal value As T)\n       Dim node As New Node(Of T)(Me, value)\n\n       If m_Tail Is Nothing Then\n           m_Head = node\n           m_Tail = m_Head\n       Else\n           node.Previous = m_Tail\n           m_Tail = node\n       End If\n   End Sub\n\n   Public ReadOnly Property Head() As Node(Of T)\n       Get\n           Return m_Head\n       End Get\n   End Property\n\n   Public ReadOnly Property Tail() As Node(Of T)\n       Get\n           Return m_Tail\n       End Get\n   End Property\n\n   Public Sub RemoveTail()\n       If m_Tail Is Nothing Then Return\n\n       If m_Tail.Previous Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Tail = m_Tail.Previous\n           m_Tail.Next = Nothing\n       End If\n   End Sub\n\n   Public Sub RemoveHead()\n       If m_Head Is Nothing Then Return\n\n       If m_Head.Next Is Nothing Then \n           m_Head = Nothing\n           m_Tail = Nothing\n       Else\n           m_Head = m_Head.Next\n           m_Head.Previous = Nothing\n       End If\n   End Sub\n\nEnd Class\n\nPublic Class Node(Of T)\n   Private ReadOnly m_Value As T\n   Private m_Next As Node(Of T)\n   Private m_Previous As Node(Of T)\n   Private ReadOnly m_Parent As DoubleLinkList(Of T)\n\n   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)\n       m_Parent = parent\n       m_Value = value\n   End Sub\n\n   Public Property [Next]() As Node(Of T)\n       Get\n           Return m_Next\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Next = value\n       End Set\n   End Property\n\n   Public Property Previous() As Node(Of T)\n       Get\n           Return m_Previous\n       End Get\n       Friend Set(ByVal value As Node(Of T))\n           m_Previous = value\n       End Set\n   End Property\n\n   Public ReadOnly Property Value() As T\n       Get\n           Return m_Value\n       End Get\n   End Property\n\n   Public Sub InsertAfter(ByVal value As T)\n       If m_Next Is Nothing Then\n           m_Parent.AddTail(value)\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.AddHead(value)\n       Else\n           Dim node As New Node(Of T)(m_Parent, value)\n           node.Previous = Me\n           node.Next = Me.Next\n           Me.Next.Previous = node\n           Me.Next = node\n       End If\n   End Sub\n\n   Public Sub Remove()\n       If m_Next Is Nothing Then\n           m_Parent.RemoveTail()\n       ElseIf m_Previous Is Nothing Then\n           m_Parent.RemoveHead()\n       Else\n           m_Previous.Next = Me.Next\n           m_Next.Previous = Me.Previous\n       End If\n   End Sub\n\nEnd Class\n", "Java": "import java.util.LinkedList;\n\npublic class DoublyLinkedList {\n   \n    public static void main(String[] args) {\n        LinkedList<String> list = new LinkedList<String>();\n        list.addFirst(\"Add First\");\n        list.addLast(\"Add Last 1\");\n        list.addLast(\"Add Last 2\");\n        list.addLast(\"Add Last 1\");\n        traverseList(list);\n        \n        list.removeFirstOccurrence(\"Add Last 1\");\n        traverseList(list);\n    }\n    \n    private static void traverseList(LinkedList<String> list) {\n        System.out.println(\"Traverse List:\");\n        for ( int i = 0 ; i < list.size() ; i++ ) {\n            System.out.printf(\"Element number %d - Element value = '%s'%n\", i, list.get(i));\n        }\n        System.out.println();\n    }\n    \n}\n"}
{"id": 45501, "name": "Letter frequency", "VB": "\n\n\n\n\n\n\n\n\nTYPE regChar\n  Character AS STRING * 3\n  Count AS LONG\nEND TYPE\n\n\nDIM iChar AS INTEGER\nDIM iCL AS INTEGER\nDIM iCountChars AS INTEGER\nDIM iFile AS INTEGER\nDIM i AS INTEGER\nDIM lMUC AS LONG\nDIM iMUI AS INTEGER\nDIM lLUC AS LONG\nDIM iLUI AS INTEGER\nDIM iMaxIdx AS INTEGER\nDIM iP AS INTEGER\nDIM iPause AS INTEGER\nDIM iPMI AS INTEGER\nDIM iPrint AS INTEGER\nDIM lHowMany AS LONG\nDIM lTotChars AS LONG\nDIM sTime AS SINGLE\nDIM strFile AS STRING\nDIM strTxt AS STRING\nDIM strDate AS STRING\nDIM strTime AS STRING\nDIM strKey AS STRING\nCONST LngReg = 256\nCONST Letters = 1\nCONST FALSE = 0\nCONST TRUE = NOT FALSE\n\n\n\n\nstrDate = DATE$\nstrTime = TIME$\niFile = FREEFILE\n\n\nDO\n  CLS\n  PRINT \"This program counts letters or characters in a text file.\"\n  PRINT\n  INPUT \"File to open: \", strFile\n  OPEN strFile FOR BINARY AS #iFile\n  IF LOF(iFile) > 0 THEN\n    PRINT \"Count: 1) Letters 2) Characters (1 or 2)\";\n    DO\n      strKey = INKEY$\n    LOOP UNTIL strKey = \"1\" OR strKey = \"2\"\n    PRINT \". Option selected: \"; strKey\n    iCL = VAL(strKey)\n    sTime = TIMER\n    iP = POS(0)\n    lHowMany = LOF(iFile)\n    strTxt = SPACE$(LngReg)\n\n    IF iCL = Letters THEN\n      iMaxIdx = 26\n    ELSE\n      iMaxIdx = 255\n    END IF\n\n    IF iMaxIdx <> iPMI THEN\n      iPMI = iMaxIdx\n      REDIM rChar(0 TO iMaxIdx) AS regChar\n\n      FOR i = 0 TO iMaxIdx\n        IF iCL = Letters THEN\n          strTxt = CHR$(i + 65)\n          IF i = 26 THEN strTxt = CHR$(165)\n        ELSE\n          SELECT CASE i\n            CASE 0: strTxt = \"nul\"\n            CASE 7: strTxt = \"bel\"\n            CASE 9: strTxt = \"tab\"\n            CASE 10: strTxt = \"lf\"\n            CASE 11: strTxt = \"vt\"\n            CASE 12: strTxt = \"ff\"\n            CASE 13: strTxt = \"cr\"\n            CASE 28: strTxt = \"fs\"\n            CASE 29: strTxt = \"gs\"\n            CASE 30: strTxt = \"rs\"\n            CASE 31: strTxt = \"us\"\n            CASE 32: strTxt = \"sp\"\n            CASE ELSE: strTxt = CHR$(i)\n          END SELECT\n        END IF\n        rChar(i).Character = strTxt\n      NEXT i\n    ELSE\n      FOR i = 0 TO iMaxIdx\n        rChar(i).Count = 0\n      NEXT i\n    END IF\n\n    PRINT \"Looking for \";\n    IF iCL = Letters THEN PRINT \"letters.\";  ELSE PRINT \"characters.\";\n    PRINT \" File is\"; STR$(lHowMany); \" in size. Working\"; : COLOR 23: PRINT \"...\"; : COLOR (7)\n    DO WHILE LOC(iFile) < LOF(iFile)\n      IF LOC(iFile) + LngReg > LOF(iFile) THEN\n        strTxt = SPACE$(LOF(iFile) - LOC(iFile))\n      END IF\n      GET #iFile, , strTxt\n      FOR i = 1 TO LEN(strTxt)\n        IF iCL = Letters THEN\n          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))\n          SELECT CASE iChar\n            CASE 164: iChar = 165\n            CASE 160: iChar = 65\n            CASE 130, 144: iChar = 69\n            CASE 161: iChar = 73\n            CASE 162: iChar = 79\n            CASE 163, 129: iChar = 85\n          END SELECT\n          iChar = iChar - 65\n          \n          \n          IF iChar >= 0 AND iChar <= 25 THEN\n            rChar(iChar).Count = rChar(iChar).Count + 1\n          ELSEIF iChar = 100 THEN \n            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1\n          END IF\n        ELSE\n          iChar = ASC(MID$(strTxt, i, 1))\n          rChar(iChar).Count = rChar(iChar).Count + 1\n        END IF\n      NEXT i\n    LOOP\n    CLOSE #iFile\n\n    \n    lMUC = 0\n    iMUI = 0\n    lLUC = 2147483647\n    iLUI = 0\n    iPrint = FALSE\n    lTotChars = 0\n    iCountChars = 0\n    iPause = FALSE\n    CLS\n    IF iCL = Letters THEN PRINT \"Letters found: \";  ELSE PRINT \"Characters found: \";\n    FOR i = 0 TO iMaxIdx\n      \n      IF lMUC < rChar(i).Count THEN\n        lMUC = rChar(i).Count\n        iMUI = i\n      END IF\n\n      \n      IF rChar(i).Count > 0 THEN\n        strTxt = \"\"\n        IF iPrint THEN strTxt = \", \" ELSE iPrint = TRUE\n        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))\n        strTxt = strTxt + \"=\" + LTRIM$(STR$(rChar(i).Count))\n        iP = POS(0)\n        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN\n          PRINT \",\"\n          IF CSRLIN >= 23 AND NOT iPause THEN\n            iPause = TRUE\n            PRINT \"Press a key to continue...\"\n            DO\n              strKey = INKEY$\n            LOOP UNTIL strKey <> \"\"\n          END IF\n          strTxt = MID$(strTxt, 3)\n        END IF\n        PRINT strTxt;\n        lTotChars = lTotChars + rChar(i).Count\n        iCountChars = iCountChars + 1\n\n        \n        IF lLUC > rChar(i).Count THEN\n          lLUC = rChar(i).Count\n          iLUI = i\n        END IF\n      END IF\n    NEXT i\n\n    PRINT \".\"\n\n    \n    PRINT\n    PRINT \"File analyzed....................: \"; strFile\n    PRINT \"Looked for.......................: \"; : IF iCL = Letters THEN PRINT \"Letters\" ELSE PRINT \"Characters\"\n    PRINT \"Total characters in file.........:\"; lHowMany\n    PRINT \"Total characters counted.........:\"; lTotChars\n    IF iCL = Letters THEN PRINT \"Characters discarded on count....:\"; lHowMany - lTotChars\n    PRINT \"Distinct characters found in file:\"; iCountChars; \"of\"; iMaxIdx + 1\n    PRINT \"Most used character was..........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lMUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n    PRINT \" (\"; LTRIM$(STR$(rChar(iMUI).Count)); \" times)\"\n    PRINT \"Least used character was.........: \";\n      iPrint = FALSE\n      FOR i = 0 TO iMaxIdx\n        IF rChar(i).Count = lLUC THEN\n          IF iPrint THEN PRINT \", \";  ELSE iPrint = TRUE\n          PRINT RTRIM$(LTRIM$(rChar(i).Character));\n        END IF\n      NEXT i\n      PRINT \" (\"; LTRIM$(STR$(rChar(iLUI).Count)); \" times)\"\n    PRINT \"Time spent in the process........:\"; TIMER - sTime; \"seconds\"\n  ELSE\n    \n    CLOSE #iFile\n    KILL strFile\n    PRINT\n    PRINT \"File does not exist.\"\n  END IF\n\n  \n  PRINT\n  PRINT \"Again? (Y/n)\"\n  DO\n    strTxt = UCASE$(INKEY$)\n  LOOP UNTIL strTxt = \"N\" OR strTxt = \"Y\" OR strTxt = CHR$(13) OR strTxt = CHR$(27)\nLOOP UNTIL strTxt = \"N\" OR strTxt = CHR$(27)\n\nCLS\nPRINT \"End of execution.\"\nPRINT \"Start time: \"; strDate; \" \"; strTime; \", end time: \"; DATE$; \" \"; TIME$; \".\"\nEND\n\n", "Java": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n"}
{"id": 45502, "name": "Increment a numerical string", "VB": "    Dim s As String = \"123\"\n\n    s = CStr(CInt(\"123\") + 1)\n    \n    s = (CInt(\"123\") + 1).ToString\n", "Java": "String s = \"12345\";\nIntLiteral lit1 = new IntLiteral(s);\nIntLiteral lit2 = 6789;\n++lit1; \n++lit2; \n"}
{"id": 45503, "name": "Strip a set of characters from a string", "VB": "Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)\nDim i As Integer, stReplace As String\n    If bSpace = True Then\n        stReplace = \" \"\n    Else\n        stReplace = \"\"\n    End If\n    For i = 1 To Len(stStripChars)\n        stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)\n    Next i\n    StripChars = stString\nEnd Function\n", "Java": "class StripChars {\n    public static String stripChars(String inString, String toStrip) {\n        return inString.replaceAll(\"[\" + toStrip + \"]\", \"\");\n    }\n\n    public static void main(String[] args) {\n        String sentence = \"She was a soul stripper. She took my heart!\";\n        String chars = \"aei\";\n        System.out.println(\"sentence: \" + sentence);\n        System.out.println(\"to strip: \" + chars);\n        System.out.println(\"stripped: \" + stripChars(sentence, chars));\n    }\n}\n"}
{"id": 45504, "name": "Averages_Arithmetic mean", "VB": "Private Function mean(v() As Double, ByVal leng As Integer) As Variant\n    Dim sum As Double, i As Integer\n    sum = 0: i = 0\n    For i = 0 To leng - 1\n        sum = sum + vv\n    Next i\n    If leng = 0 Then\n        mean = CVErr(xlErrDiv0)\n    Else\n        mean = sum / leng\n    End If\nEnd Function\nPublic Sub main()\n    Dim v(4) As Double\n    Dim i As Integer, leng As Integer\n    v(0) = 1#\n    v(1) = 2#\n    v(2) = 2.178\n    v(3) = 3#\n    v(4) = 3.142\n    For leng = 5 To 0 Step -1\n        Debug.Print \"mean[\";\n        For i = 0 To leng - 1\n            Debug.Print IIf(i, \"; \" & v(i), \"\" & v(i));\n        Next i\n        Debug.Print \"] = \"; mean(v, leng)\n    Next leng\nEnd Sub\n", "Java": "public static double avg(double... arr) {\n    double sum = 0.0;\n    for (double x : arr) {\n        sum += x;\n    }\n    return sum / arr.length;\n}\n"}
{"id": 45505, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 45506, "name": "Abbreviations, simple", "VB": "Private Function ValidateUserWords(userstring As String) As String\n    Dim s As String\n    Dim user_words() As String\n    Dim command_table As Scripting.Dictionary\n    Set command_table = New Scripting.Dictionary\n    Dim abbreviations As Scripting.Dictionary\n    Set abbreviations = New Scripting.Dictionary\n    abbreviations.CompareMode = TextCompare\n    Dim commandtable() As String\n    Dim commands As String\n    s = s & \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n    s = s & \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n    s = s & \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n    s = s & \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n    s = s & \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n    s = s & \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n    s = s & \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n    s = s & \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n    commandtable = Split(s, \" \")\n    Dim i As Integer, word As Variant, number As Integer\n    For i = LBound(commandtable) To UBound(commandtable)\n        word = commandtable(i)\n        If Len(word) > 0 Then\n            i = i + 1\n            Do While Len(commandtable(i)) = 0: i = i + 1: Loop\n            number = Val(commandtable(i))\n            If number > 0 Then\n                command_table.Add Key:=word, Item:=number\n            Else\n                command_table.Add Key:=word, Item:=Len(word)\n                i = i - 1\n            End If\n        End If\n    Next i\n    For Each word In command_table\n        For i = command_table(word) To Len(word)\n            On Error Resume Next\n            abbreviations.Add Key:=Left(word, i), Item:=UCase(word)\n        Next i\n    Next word\n    user_words() = Split(userstring, \" \")\n    For Each word In user_words\n        If Len(word) > 0 Then\n            If abbreviations.exists(word) Then\n                commands = commands & abbreviations(word) & \" \"\n            Else\n                commands = commands & \"*error* \"\n            End If\n        End If\n    Next word\n    ValidateUserWords = commands\nEnd Function\nPublic Sub program()\n    Dim guserstring As String\n    guserstring = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    Debug.Print \"user words:\", guserstring\n    Debug.Print \"full words:\", ValidateUserWords(guserstring)\nEnd Sub\n", "Java": "import java.util.*;\n\npublic class Abbreviations {\n    public static void main(String[] args) {\n        CommandList commands = new CommandList(commandTable);\n        String input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n        System.out.println(\" input: \" + input);\n        System.out.println(\"output: \" + test(commands, input));\n    }\n\n    private static String test(CommandList commands, String input) {\n        StringBuilder output = new StringBuilder();\n        Scanner scanner = new Scanner(input);\n        while (scanner.hasNext()) {\n            String word = scanner.next();\n            if (output.length() > 0)\n                output.append(' ');\n            Command cmd = commands.findCommand(word);\n            if (cmd != null)\n                output.append(cmd.cmd);\n            else\n                output.append(\"*error*\");\n        }\n        return output.toString();\n    }\n\n    private static String commandTable =\n        \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n        \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n        \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n        \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n        \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n        \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n        \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n        \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\n    private static class Command {\n        private Command(String cmd, int minLength) {\n             this.cmd = cmd;\n             this.minLength = minLength;\n        }\n        private boolean match(String str) {\n            int olen = str.length();\n            return olen >= minLength && olen <= cmd.length()\n                && cmd.regionMatches(true, 0, str, 0, olen);\n        }\n        private String cmd;\n        private int minLength;\n    }\n\n    private static Integer parseInteger(String word) {\n        try {\n            return Integer.valueOf(word);\n        } catch (NumberFormatException ex) {\n            return null;\n        }\n    }\n\n    private static class CommandList {\n        private CommandList(String table) {\n            Scanner scanner = new Scanner(table);\n            List<String> words = new ArrayList<>();\n            while (scanner.hasNext()) {\n                String word = scanner.next();\n                words.add(word.toUpperCase());\n            }\n            for (int i = 0, n = words.size(); i < n; ++i) {\n                String word = words.get(i);\n                \n                \n                \n                int len = word.length();\n                if (i + 1 < n) {\n                    Integer number = parseInteger(words.get(i + 1));\n                    if (number != null) {\n                        len = number.intValue();\n                        ++i;\n                    }\n                }\n                commands.add(new Command(word, len));\n            }\n        }\n        private Command findCommand(String word) {\n            for (Command command : commands) {\n                if (command.match(word))\n                    return command;\n            }\n            return null;\n        }\n        private List<Command> commands = new ArrayList<>();\n    }\n}\n"}
{"id": 45507, "name": "Tokenize a string with escaping", "VB": "Private Function tokenize(s As String, sep As String, esc As String) As Collection\n    Dim ret As New Collection\n    Dim this As String\n    Dim skip As Boolean\n     \n    If Len(s) <> 0 Then\n        For i = 1 To Len(s)\n            si = Mid(s, i, 1)\n            If skip Then\n                this = this & si\n                skip = False\n            Else\n                If si = esc Then\n                    skip = True\n                Else\n                    If si = sep Then\n                        ret.Add this\n                        this = \"\"\n                    Else\n                        this = this & si\n                    End If\n                End If\n            End If\n        Next i\n        ret.Add this\n    End If\n    Set tokenize = ret\nEnd Function\n\nPublic Sub main()\n    Dim out As Collection\n    Set out = tokenize(\"one^|uno||three^^^^|four^^^|^cuatro|\", \"|\", \"^\")\n    Dim outstring() As String\n    ReDim outstring(out.Count - 1)\n    For i = 0 To out.Count - 1\n        outstring(i) = out(i + 1)\n    Next i\n    Debug.Print Join(outstring, \", \")\nEnd Sub\n", "Java": "import java.util.*;\n\npublic class TokenizeStringWithEscaping {\n\n    public static void main(String[] args) {\n        String sample = \"one^|uno||three^^^^|four^^^|^cuatro|\";\n        char separator = '|';\n        char escape = '^';\n\n        System.out.println(sample);\n        try {\n            System.out.println(tokenizeString(sample, separator, escape));\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n    }\n\n    public static List<String> tokenizeString(String s, char sep, char escape)\n            throws Exception {\n        List<String> tokens = new ArrayList<>();\n        StringBuilder sb = new StringBuilder();\n\n        boolean inEscape = false;\n        for (char c : s.toCharArray()) {\n            if (inEscape) {\n                inEscape = false;\n            } else if (c == escape) {\n                inEscape = true;\n                continue;\n            } else if (c == sep) {\n                tokens.add(sb.toString());\n                sb.setLength(0);\n                continue;\n            }\n            sb.append(c);\n        }\n        if (inEscape)\n            throw new Exception(\"Invalid terminal escape\");\n\n        tokens.add(sb.toString());\n\n        return tokens;\n    }\n}\n"}
{"id": 45508, "name": "Hello world_Text", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 45509, "name": "Hello world_Text", "VB": "Public Sub hello_world_text\n    Debug.Print \"Hello World!\"\nEnd Sub\n", "Java": "module HelloWorld\n    {\n    void run()\n        {\n        @Inject Console console;\n        console.print(\"Hello World!\");\n        }\n    }\n"}
{"id": 45510, "name": "Forward difference", "VB": "Module ForwardDifference\n\n    Sub Main()\n        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})\n        For i As UInteger = 0 To 9\n            Console.WriteLine(String.Join(\" \", (From n In Difference(i, lNum) Select String.Format(\"{0,5}\", n)).ToArray()))\n        Next\n        Console.ReadKey()\n    End Sub\n\n    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)\n        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException(\"Level\", \"Level must be less than number of items in Numbers\")\n\n        For i As Integer = 1 To Level\n            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _\n                       Select Numbers(n + 1) - Numbers(n)).ToList()\n        Next\n\n        Return Numbers\n    End Function\n\nEnd Module\n", "Java": "import java.util.Arrays;\npublic class FD {\n    public static void main(String args[]) {\n        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n        System.out.println(Arrays.toString(dif(a, 1)));\n        System.out.println(Arrays.toString(dif(a, 2)));\n        System.out.println(Arrays.toString(dif(a, 9)));\n        System.out.println(Arrays.toString(dif(a, 10)));      \n        System.out.println(Arrays.toString(dif(a, 11)));\n        System.out.println(Arrays.toString(dif(a, -1)));\n        System.out.println(Arrays.toString(dif(a, 0)));\n    }\n\n    public static double[] dif(double[] a, int n) {\n        if (n < 0)\n            return null; \n\n        for (int i = 0; i < n && a.length > 0; i++) {\n            double[] b = new double[a.length - 1];\n            for (int j = 0; j < b.length; j++){\n                b[j] = a[j+1] - a[j];\n            }\n            a = b; \n        }\n        return a;\n    }\n}\n"}
{"id": 45511, "name": "Primality by trial division", "VB": "Option Explicit\n\nSub FirstTwentyPrimes()\nDim count As Integer, i As Long, t(19) As String\n   Do\n      i = i + 1\n      If IsPrime(i) Then\n         t(count) = i\n         count = count + 1\n      End If\n   Loop While count <= UBound(t)\n   Debug.Print Join(t, \", \")\nEnd Sub\n\nFunction IsPrime(Nb As Long) As Boolean\n   If Nb = 2 Then\n      IsPrime = True\n   ElseIf Nb < 2 Or Nb Mod 2 = 0 Then\n      Exit Function\n   Else\n      Dim i As Long\n      For i = 3 To Sqr(Nb) Step 2\n         If Nb Mod i = 0 Then Exit Function\n      Next\n      IsPrime = True\n   End If\nEnd Function\n", "Java": "public static boolean prime(long a){\n   if(a == 2){\n      return true;\n   }else if(a <= 1 || a % 2 == 0){\n      return false;\n   }\n   long max = (long)Math.sqrt(a);\n   for(long n= 3; n <= max; n+= 2){\n      if(a % n == 0){ return false; }\n   }\n   return true;\n}\n"}
{"id": 45512, "name": "Evaluate binomial coefficients", "VB": "Function binomial(n,k)\n\tbinomial = factorial(n)/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n", "Java": "public class Binomial {\n\n    \n    private static long binomialInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static Object binomialIntReliable(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        long binom = 1;\n        for (int i = 1; i <= k; i++) {\n            try {\n                binom = Math.multiplyExact(binom, n + 1 - i) / i;\n            } catch (ArithmeticException e) {\n                return \"overflow\";\n            }\n        }\n        return binom;\n    }\n\n    \n    \n    private static double binomialFloat(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        double binom = 1.0;\n        for (int i = 1; i <= k; i++)\n            binom = binom * (n + 1 - i) / i;\n        return binom;\n    }\n\n    \n    private static BigInteger binomialBigInt(int n, int k) {\n        if (k > n - k)\n            k = n - k;\n\n        BigInteger binom = BigInteger.ONE;\n        for (int i = 1; i <= k; i++) {\n            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n            binom = binom.divide(BigInteger.valueOf(i));\n        }\n        return binom;\n    }\n\n    private static void demo(int n, int k) {\n        List<Object> data = Arrays.asList(\n                n,\n                k,\n                binomialInt(n, k),\n                binomialIntReliable(n, k),\n                binomialFloat(n, k),\n                binomialBigInt(n, k));\n\n        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n    }\n\n    public static void main(String[] args) {\n        demo(5, 3);\n        demo(1000, 300);\n    }\n}\n"}
{"id": 45513, "name": "Collections", "VB": "Dim coll As New Collection\ncoll.Add \"apple\"\ncoll.Add \"banana\"\n", "Java": "List arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\narrayList.add(0); \n\n\n\nList<Integer> myarrlist = new ArrayList<Integer>();\n\n\nint sum;\nfor(int i = 0; i < 10; i++) {\n    myarrlist.add(i);\n}\n"}
{"id": 45514, "name": "Singly-linked list_Traversal", "VB": "Private Sub Iterate(ByVal list As LinkedList(Of Integer))\n    Dim node = list.First\n    Do Until node Is Nothing\n        node = node.Next\n    Loop\n    End Sub\n", "Java": "LinkedList<Type> list = new LinkedList<Type>();\n\nfor(Type i: list){\n  \n  System.out.println(i);\n}\n"}
{"id": 45515, "name": "Bitmap_Write a PPM file", "VB": "Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)\n   Dim header As String = String.Format(\"P6{0}{1}{2}{3}{0}255{0}\", vbLf, rasterBitmap.Width, \" \"c, rasterBitmap.Height)\n   Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)\n   Dim bytes(bufferSize - 1) As Byte\n   Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)\n   Dim index As Integer = header.Length\n   For y As Integer = 0 To rasterBitmap.Height - 1\n      For x As Integer = 0 To rasterBitmap.Width - 1\n         Dim color As Rgb = rasterBitmap.GetPixel(x, y)\n         bytes(index) = color.R\n         bytes(index + 1) = color.G\n         bytes(index + 2) = color.B\n         index += 3\n      Next\n   Next\n   My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)\nEnd Sub\n", "Java": "import java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\npublic class PPMWriter {\n\n    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {\n        file.delete();\n\n        try (var os = new FileOutputStream(file, true);\n             var bw = new BufferedOutputStream(os)) {\n            var header = String.format(\"P6\\n%d %d\\n255\\n\",\n                    bitmap.getWidth(), bitmap.getHeight());\n\n            bw.write(header.getBytes(StandardCharsets.US_ASCII));\n\n            for (var y = 0; y < bitmap.getHeight(); y++) {\n                for (var x = 0; x < bitmap.getWidth(); x++) {\n                    var pixel = bitmap.getPixel(x, y);\n                    bw.write(pixel.getRed());\n                    bw.write(pixel.getGreen());\n                    bw.write(pixel.getBlue());\n                }\n            }\n        }\n    }\n}\n"}
{"id": 45516, "name": "Delete a file", "VB": "Option Explicit\n\nSub DeleteFileOrDirectory()\nDim myPath As String\n    myPath = \"C:\\Users\\surname.name\\Desktop\\Docs\"\n\n    Kill myPath & \"\\input.txt\"\n\n    RmDir myPath\nEnd Sub\n", "Java": "import java.io.File;\n\npublic class FileDeleteTest {\n    public static boolean deleteFile(String filename) {\n        boolean exists = new File(filename).delete();\n        return exists;\n    }\n    \n    public static void test(String type, String filename) {\n        System.out.println(\"The following \" + type + \" called \" + filename + \n            (deleteFile(filename) ? \" was deleted.\" : \" could not be deleted.\")\n        );\n    }\n\n    public static void main(String args[]) {\n        test(\"file\", \"input.txt\");\n        test(\"file\", File.seperator + \"input.txt\");\n        test(\"directory\", \"docs\");\n        test(\"directory\", File.seperator + \"docs\" + File.seperator);\n    }\n}\n"}
{"id": 45517, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 45518, "name": "Average loop length", "VB": "Const MAX = 20\nConst ITER = 1000000\n \nFunction expected(n As Long) As Double\n    Dim sum As Double\n    For i = 1 To n\n        sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)\n    Next i\n    expected = sum\nEnd Function\n \nFunction test(n As Long) As Double\n    Dim count As Long\n    Dim x As Long, bits As Long\n    For i = 1 To ITER\n        x = 1\n        bits = 0\n        Do While Not bits And x\n            count = count + 1\n            bits = bits Or x\n            x = 2 ^ (Int(n * Rnd()))\n        Loop\n    Next i\n    test = count / ITER\nEnd Function\n \nPublic Sub main()\n    Dim n As Long\n    Debug.Print \" n     avg.     exp.  (error%)\"\n    Debug.Print \"==   ======   ======  ========\"\n    For n = 1 To MAX\n        av = test(n)\n        ex = expected(n)\n        Debug.Print Format(n, \"@@\"); \"  \"; Format(av, \"0.0000\"); \"   \";\n        Debug.Print Format(ex, \"0.0000\"); \"  (\"; Format(Abs(1 - av / ex), \"0.000%\"); \")\"\n    Next n\nEnd Sub\n", "Java": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n    private static final int N = 100000;\n\n    \n    private static double analytical(int n) {\n        double[] factorial = new double[n + 1];\n        double[] powers = new double[n + 1];\n        powers[0] = 1.0;\n        factorial[0] = 1.0;\n        for (int i = 1; i <= n; i++) {\n            factorial[i] = factorial[i - 1] * i;\n            powers[i] = powers[i - 1] * n;\n        }\n        double sum = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            sum += factorial[n] / factorial[n - i] / powers[i];\n        }\n        return sum;\n    }\n\n    private static double average(int n) {\n        Random rnd = new Random();\n        double sum = 0.0;\n        for (int a = 0; a < N; a++) {\n            int[] random = new int[n];\n            for (int i = 0; i < n; i++) {\n                random[i] = rnd.nextInt(n);\n            }\n            Set<Integer> seen = new HashSet<>(n);\n            int current = 0;\n            int length = 0;\n            while (seen.add(current)) {\n                length++;\n                current = random[current];\n            }\n            sum += length;\n        }\n        return sum / N;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\" N    average    analytical    (error)\");\n        System.out.println(\"===  =========  ============  =========\");\n        for (int i = 1; i <= 20; i++) {\n            double avg = average(i);\n            double ana = analytical(i);\n            System.out.println(String.format(\"%3d  %9.4f  %12.4f  (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n        }\n    }\n}\n"}
{"id": 45519, "name": "String interpolation (included)", "VB": "Dim name as String = \"J. Doe\"\nDim balance as Double = 123.45\nDim prompt as String = String.Format(\"Hello {0}, your balance is {1}.\", name, balance)\nConsole.WriteLine(prompt)\n", "Java": "String original = \"Mary had a X lamb\";\nString little = \"little\";\nString replaced = original.replace(\"X\", little); \nSystem.out.println(replaced);\n\nSystem.out.printf(\"Mary had a %s lamb.\", little);\n\nString formatted = String.format(\"Mary had a %s lamb.\", little);\nSystem.out.println(formatted);\n"}
{"id": 45520, "name": "Determinant and permanent", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 45521, "name": "Determinant and permanent", "VB": "Module Module1\n\n    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)\n        Dim length = a.GetLength(0) - 1\n        Dim result(length - 1, length - 1) As Double\n        For i = 1 To length\n            For j = 1 To length\n                If i < x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i - 1, j - 1)\n                ElseIf i >= x AndAlso j < y Then\n                    result(i - 1, j - 1) = a(i, j - 1)\n                ElseIf i < x AndAlso j >= y Then\n                    result(i - 1, j - 1) = a(i - 1, j)\n                Else\n                    result(i - 1, j - 1) = a(i, j)\n                End If\n            Next\n        Next\n        Return result\n    End Function\n\n    Function Det(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sign = 1\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))\n                sign *= -1\n            Next\n            Return sum\n        End If\n    End Function\n\n    Function Perm(a As Double(,)) As Double\n        If a.GetLength(0) = 1 Then\n            Return a(0, 0)\n        Else\n            Dim sum = 0.0\n            For i = 1 To a.GetLength(0)\n                sum += a(0, i - 1) * Perm(Minor(a, 0, i))\n            Next\n            Return sum\n        End If\n    End Function\n\n    Sub WriteLine(a As Double(,))\n        For i = 1 To a.GetLength(0)\n            Console.Write(\"[\")\n            For j = 1 To a.GetLength(1)\n                If j > 1 Then\n                    Console.Write(\", \")\n                End If\n                Console.Write(a(i - 1, j - 1))\n            Next\n            Console.WriteLine(\"]\")\n        Next\n    End Sub\n\n    Sub Test(a As Double(,))\n        If a.GetLength(0) <> a.GetLength(1) Then\n            Throw New ArgumentException(\"The dimensions must be equal\")\n        End If\n\n        WriteLine(a)\n        Console.WriteLine(\"Permanant  : {0}\", Perm(a))\n        Console.WriteLine(\"Determinant: {0}\", Det(a))\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Test({{1, 2}, {3, 4}})\n        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})\n        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})\n    End Sub\n\nEnd Module\n", "Java": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i<length;i++) for(int j=0;j<length;j++){\n\t\t\tif(i<x && j<y){\n\t\t\t\tresult[i][j] = a[i][j];\n\t\t\t}else if(i>=x && j<y){\n\t\t\t\tresult[i][j] = a[i+1][j];\n\t\t\t}else if(i<x && j>=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ \n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += sign * a[0][i] * det(minor(a,0,i));\n\t\t\t\tsign *= -1;\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static double perm(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i<a.length;i++){\n\t\t\t\tsum += a[0][i] * perm(minor(a,0,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\t}\n\tpublic static void main(String args[]){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint size = sc.nextInt();\n\t\tdouble[][] a = new double[size][size];\n\t\tfor(int i=0;i<size;i++) for(int j=0;j<size;j++){\n\t\t\ta[i][j] = sc.nextDouble();\n\t\t}\n\t\tsc.close();\n\t\tSystem.out.println(\"Determinant: \"+det(a));\n\t\tSystem.out.println(\"Permanent: \"+perm(a));\n\t}\n}\n"}
{"id": 45522, "name": "Bitwise operations", "Go": "package main\n\nimport \"fmt\"\n\nfunc bitwise(a, b int16) {\n\tfmt.Printf(\"a:   %016b\\n\", uint16(a))\n\tfmt.Printf(\"b:   %016b\\n\", uint16(b))\n\n\t\n\tfmt.Printf(\"and: %016b\\n\", uint16(a&b))\n\tfmt.Printf(\"or:  %016b\\n\", uint16(a|b))\n\tfmt.Printf(\"xor: %016b\\n\", uint16(a^b))\n\tfmt.Printf(\"not: %016b\\n\", uint16(^a))\n\n\tif b < 0 {\n\t\tfmt.Println(\"Right operand is negative, but all shifts require an unsigned right operand (shift distance).\")\n\t\treturn\n\t}\n\tua := uint16(a)\n\tub := uint32(b)\n\n\t\n\tfmt.Printf(\"shl: %016b\\n\", uint16(ua<<ub))\n\tfmt.Printf(\"shr: %016b\\n\", uint16(ua>>ub))\n\n\t\n\tfmt.Printf(\"las: %016b\\n\", uint16(a<<ub))\n\tfmt.Printf(\"ras: %016b\\n\", uint16(a>>ub))\n\n\t\n\tfmt.Printf(\"rol: %016b\\n\", uint16(a<<ub|int16(uint16(a)>>(16-ub))))\n\tfmt.Printf(\"ror: %016b\\n\", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))\n}\n\nfunc main() {\n\tvar a, b int16 = -460, 6\n\tbitwise(a, b)\n}\n", "C": "void bitwise(int a, int b)\n{\n  printf(\"a and b: %d\\n\", a & b);\n  printf(\"a or b: %d\\n\", a | b);\n  printf(\"a xor b: %d\\n\", a ^ b);\n  printf(\"not a: %d\\n\", ~a);\n  printf(\"a << n: %d\\n\", a << b); \n  printf(\"a >> n: %d\\n\", a >> b); \n  \n  unsigned int c = a;\n  printf(\"c >> b: %d\\n\", c >> b); \n  \n  return 0;\n}\n"}
{"id": 45523, "name": "Dragon curve", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math\"\n    \"os\"\n)\n\n\n\nconst sep = 512\n\nconst depth = 14\n\nvar s = math.Sqrt2 / 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 / 6\n    height := sep * 4 / 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep/2, sep*5/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \n        \n        \n        \n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen / scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x/scale, y/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng / 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 / 2 + 2;\n\n\t\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] / maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n"}
{"id": 45524, "name": "Read a file line by line", "Go": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile)\n}\n\nfunc main() {\n\t\n\tinputFile, err := os.Open(\"byline.go\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening input file:\", err)\n\t}\n\n\t\n\t\n\t\n\tdefer inputFile.Close()\n\n\tscanner := bufio.NewScanner(inputFile)\n\n\t\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n\n\t\n\t\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(scanner.Err())\n\t}\n}\n", "C": "\n\n#include <conio.h>\n#include <stdio.h>\n\nint main()\n{\n    int n1, n2, n3;\n\n    printf( \"\\n   Introduzca el primer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n1 );\n    printf( \"\\n   Introduzca el segundo n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n2 );\n    printf( \"\\n   Introduzca el tercer n%cmero (entero): \", 163 );\n    scanf( \"%d\", &n3 );\n\n    if ( n1 >= n2 && n1 >= n3 )\n        printf( \"\\n   %d es el mayor.\", n1 );\n    else\n\n        if ( n2 > n3 )\n            printf( \"\\n   %d es el mayor.\", n2 );\n        else\n            printf( \"\\n   %d es el mayor.\", n3 );\n \n    getch(); \n\n    return 0;\n}\n"}
{"id": 45525, "name": "Doubly-linked list_Element insertion", "Go": "package main\n\nimport \"fmt\"\n\ntype dlNode struct {\n    string\n    next, prev *dlNode\n}\n\ntype dlList struct {\n    head, tail *dlNode\n}\n\nfunc (list *dlList) String() string {\n    if list.head == nil {\n        return fmt.Sprint(list.head)\n    }\n    r := \"[\" + list.head.string\n    for p := list.head.next; p != nil; p = p.next {\n        r += \" \" + p.string\n    }\n    return r + \"]\"\n}\n\nfunc (list *dlList) insertTail(node *dlNode) {\n    if list.tail == nil {\n        list.head = node\n    } else {\n        list.tail.next = node\n    }\n    node.next = nil\n    node.prev = list.tail\n    list.tail = node\n}\n\nfunc (list *dlList) insertAfter(existing, insert *dlNode) {\n    insert.prev = existing\n    insert.next = existing.next\n    existing.next.prev = insert\n    existing.next = insert\n    if existing == list.tail {\n        list.tail = insert\n    }\n}\n\nfunc main() {\n    dll := &dlList{}\n    fmt.Println(dll)\n    a := &dlNode{string: \"A\"}\n    dll.insertTail(a)\n    dll.insertTail(&dlNode{string: \"B\"})\n    fmt.Println(dll)\n    dll.insertAfter(a, &dlNode{string: \"C\"})\n    fmt.Println(dll)\n}\n", "C": "void insert(link* anchor, link* newlink) {\n  newlink->next = anchor->next;\n  newlink->prev = anchor;\n  (newlink->next)->prev = newlink;\n  anchor->next = newlink;\n}\n"}
{"id": 45526, "name": "Smarandache prime-digital sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar b = new(big.Int)\n\nfunc isSPDSPrime(n uint64) bool {\n    nn := n\n    for nn > 0 {\n        r := nn % 10\n        if r != 2 && r != 3 && r != 5 && r != 7 {\n            return false\n        }\n        nn /= 10\n    }\n    b.SetUint64(n)\n    if b.ProbablyPrime(0) { \n        return true\n    }\n    return false\n}\n\nfunc listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {\n    count := countFrom\n    for n := startFrom; ; n += 2 {\n        if isSPDSPrime(n) {\n            count++\n            if !printOne {\n                fmt.Printf(\"%2d. %d\\n\", count, n)\n            }\n            if count == countTo {\n                if printOne {\n                    fmt.Println(n)\n                }\n                return n\n            }\n        }\n    }\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 terms of the Smarandache prime-digital sequence are:\")\n    fmt.Println(\" 1. 2\")\n    n := listSPDSPrimes(3, 1, 25, false)\n    fmt.Println(\"\\nHigher terms:\")\n    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}\n    for i := 1; i < len(indices); i++ {\n        fmt.Printf(\"%6d. \", indices[i])\n        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)\n    }\n}\n", "C": "#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint32_t integer;\n\ninteger next_prime_digit_number(integer n) {\n    if (n == 0)\n        return 2;\n    switch (n % 10) {\n    case 2:\n        return n + 1;\n    case 3:\n    case 5:\n        return n + 2;\n    default:\n        return 2 + next_prime_digit_number(n/10) * 10;\n    }\n}\n\nbool is_prime(integer n) {\n    if (n < 2)\n        return false;\n    if (n % 2 == 0)\n        return n == 2;\n    if (n % 3 == 0)\n        return n == 3;\n    if (n % 5 == 0)\n        return n == 5;\n    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };\n    integer p = 7;\n    for (;;) {\n        for (int i = 0; i < 8; ++i) {\n            if (p * p > n)\n                return true;\n            if (n % p == 0)\n                return false;\n            p += wheel[i];\n        }\n    }\n}\n\nint main() {\n    setlocale(LC_ALL, \"\");\n    const integer limit = 1000000000;\n    integer n = 0, max = 0;\n    printf(\"First 25 SPDS primes:\\n\");\n    for (int i = 0; n < limit; ) {\n        n = next_prime_digit_number(n);\n        if (!is_prime(n))\n            continue;\n        if (i < 25) {\n            if (i > 0)\n                printf(\" \");\n            printf(\"%'u\", n);\n        }\n        else if (i == 25)\n            printf(\"\\n\");\n        ++i;\n        if (i == 100)\n            printf(\"Hundredth SPDS prime: %'u\\n\", n);\n        else if (i == 1000)\n            printf(\"Thousandth SPDS prime: %'u\\n\", n);\n        else if (i == 10000)\n            printf(\"Ten thousandth SPDS prime: %'u\\n\", n);\n        max = n;\n    }\n    printf(\"Largest SPDS prime less than %'u: %'u\\n\", limit, max);\n    return 0;\n}\n"}
{"id": 45527, "name": "Quickselect algorithm", "Go": "package main\n\nimport \"fmt\"\n\nfunc quickselect(list []int, k int) int {\n    for {\n        \n        px := len(list) / 2\n        pv := list[px]\n        last := len(list) - 1\n        list[px], list[last] = list[last], list[px]\n        i := 0\n        for j := 0; j < last; j++ {\n            if list[j] < pv {\n                list[i], list[j] = list[j], list[i]\n                i++\n            }\n        }\n        \n        if i == k {\n            return pv\n        }\n        if k < i {\n            list = list[:i]\n        } else {\n            list[i], list[last] = list[last], list[i]\n            list = list[i+1:]\n            k -= i + 1\n        }\n    }\n}\n\nfunc main() {\n    for i := 0; ; i++ {\n        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}\n        if i == len(v) {\n            return\n        }\n        fmt.Println(quickselect(v, i))\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint qselect(int *v, int len, int k)\n{\n#\tdefine SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }\n\tint i, st, tmp;\n\n\tfor (st = i = 0; i < len - 1; i++) {\n\t\tif (v[i] > v[len-1]) continue;\n\t\tSWAP(i, st);\n\t\tst++;\n\t}\n\n\tSWAP(len-1, st);\n\n\treturn k == st\t?v[st]\n\t\t\t:st > k\t? qselect(v, st, k)\n\t\t\t\t: qselect(v + st, len - st, k - st);\n}\n\nint main(void)\n{\n#\tdefine N (sizeof(x)/sizeof(x[0]))\n\tint x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};\n\tint y[N];\n\n\tint i;\n\tfor (i = 0; i < 10; i++) {\n\t\tmemcpy(y, x, sizeof(x)); \n\t\tprintf(\"%d: %d\\n\", i, qselect(y, 10, i));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 45528, "name": "Non-decimal radices_Convert", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"strconv\"\n)\n\nfunc main () {\n    s := strconv.FormatInt(26, 16) \n    fmt.Println(s)\n\n    i, err := strconv.ParseInt(\"1a\", 16, 64) \n    if err == nil {\n        fmt.Println(i)\n    }\n    b, ok := new(big.Int).SetString(\"1a\", 16) \n    if ok {\n        fmt.Println(b)\n    }\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdint.h>\n\nchar *to_base(int64_t num, int base)\n{\n  char *tbl = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n  char buf[66] = {'\\0'};\n  char *out;\n  uint64_t n;\n  int i, len = 0, neg = 0;\n  if (base > 36) {\n    fprintf(stderr, \"base %d too large\\n\", base);\n    return 0;\n  }\n\n   \n  n = ((neg = num < 0)) ? (~num) + 1 : num;\n\n  do { buf[len++] = tbl[n % base]; } while(n /= base);\n\n  out = malloc(len + neg + 1);\n  for (i = neg; len > 0; i++) out[i] = buf[--len];\n  if (neg) out[0] = '-';\n\n  return out;\n}\n\nlong from_base(const char *num_str, int base)\n{\n  char *endptr;\n  \n  \n  int result = strtol(num_str, &endptr, base);\n  return result;\n}\n\nint main()\n{\n  int64_t x;\n  x = ~(1LL << 63) + 1;\n  printf(\"%lld in base 2: %s\\n\", x, to_base(x, 2));\n  x = 383;\n  printf(\"%lld in base 16: %s\\n\", x, to_base(x, 16));\n  return 0;\n}\n"}
{"id": 45529, "name": "Walk a directory_Recursively", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc VisitFile(fp string, fi os.FileInfo, err error) error {\n    if err != nil {\n        fmt.Println(err) \n        return nil       \n    }\n    if fi.IsDir() {\n        return nil \n    }\n    matched, err := filepath.Match(\"*.mp3\", fi.Name())\n    if err != nil {\n        fmt.Println(err) \n        return err       \n    }\n    if matched {\n        fmt.Println(fp)\n    }\n    return nil\n}\n\nfunc main() {\n    filepath.Walk(\"/\", VisitFile)\n}\n", "C": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <err.h>\n\nenum {\n\tWALK_OK = 0,\n\tWALK_BADPATTERN,\n\tWALK_NAMETOOLONG,\n\tWALK_BADIO,\n};\n\n#define WS_NONE\t\t0\n#define WS_RECURSIVE\t(1 << 0)\n#define WS_DEFAULT\tWS_RECURSIVE\n#define WS_FOLLOWLINK\t(1 << 1)\t\n#define WS_DOTFILES\t(1 << 2)\t\n#define WS_MATCHDIRS\t(1 << 3)\t\n\nint walk_recur(char *dname, regex_t *reg, int spec)\n{\n\tstruct dirent *dent;\n\tDIR *dir;\n\tstruct stat st;\n\tchar fn[FILENAME_MAX];\n\tint res = WALK_OK;\n\tint len = strlen(dname);\n\tif (len >= FILENAME_MAX - 1)\n\t\treturn WALK_NAMETOOLONG;\n\n\tstrcpy(fn, dname);\n\tfn[len++] = '/';\n\n\tif (!(dir = opendir(dname))) {\n\t\twarn(\"can't open %s\", dname);\n\t\treturn WALK_BADIO;\n\t}\n\n\terrno = 0;\n\twhile ((dent = readdir(dir))) {\n\t\tif (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')\n\t\t\tcontinue;\n\t\tif (!strcmp(dent->d_name, \".\") || !strcmp(dent->d_name, \"..\"))\n\t\t\tcontinue;\n\n\t\tstrncpy(fn + len, dent->d_name, FILENAME_MAX - len);\n\t\tif (lstat(fn, &st) == -1) {\n\t\t\twarn(\"Can't stat %s\", fn);\n\t\t\tres = WALK_BADIO;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\n\t\tif (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))\n\t\t\tcontinue;\n\n\t\t\n\t\tif (S_ISDIR(st.st_mode)) {\n\t\t\t\n\t\t\tif ((spec & WS_RECURSIVE))\n\t\t\t\twalk_recur(fn, reg, spec);\n\n\t\t\tif (!(spec & WS_MATCHDIRS)) continue;\n\t\t}\n\n\t\t\n\t\tif (!regexec(reg, fn, 0, 0, 0)) puts(fn);\n\t}\n\n\tif (dir) closedir(dir);\n\treturn res ? res : errno ? WALK_BADIO : WALK_OK;\n}\n\nint walk_dir(char *dname, char *pattern, int spec)\n{\n\tregex_t r;\n\tint res;\n\tif (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))\n\t\treturn WALK_BADPATTERN;\n\tres = walk_recur(dname, &r, spec);\n\tregfree(&r);\n\n\treturn res;\n}\n\nint main()\n{\n\tint r = walk_dir(\".\", \".\\\\.c$\", WS_DEFAULT|WS_MATCHDIRS);\n\tswitch(r) {\n\tcase WALK_OK:\t\tbreak;\n\tcase WALK_BADIO:\terr(1, \"IO error\");\n\tcase WALK_BADPATTERN:\terr(1, \"Bad pattern\");\n\tcase WALK_NAMETOOLONG:\terr(1, \"Filename too long\");\n\tdefault:\n\t\terr(1, \"Unknown error?\");\n\t}\n\treturn 0;\n}\n"}
{"id": 45530, "name": "Main step of GOST 28147-89", "Go": "package main\n\nimport \"fmt\"\n\ntype sBox [8][16]byte\n\ntype gost struct {\n    k87, k65, k43, k21 [256]byte\n    enc                []byte\n}\n\nfunc newGost(s *sBox) *gost {\n    var g gost\n    for i := range g.k87 {\n        g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]\n        g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]\n        g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]\n        g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]\n    }\n    g.enc = make([]byte, 8)\n    return &g\n}\n\nfunc (g *gost) f(x uint32) uint32 {\n    x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |\n        uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])\n    return x<<11 | x>>(32-11)\n}\n\n\n\n\n\n\nvar cbrf = sBox{\n    {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},\n    {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},\n    {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},\n    {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},\n    {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},\n    {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},\n    {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},\n    {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},\n}\n\nfunc u32(b []byte) uint32 {\n    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc b4(u uint32, b []byte) {\n    b[0] = byte(u)\n    b[1] = byte(u >> 8)\n    b[2] = byte(u >> 16)\n    b[3] = byte(u >> 24)\n}\n\nfunc (g *gost) mainStep(input []byte, key []byte) {\n    key32 := u32(key)\n    input1 := u32(input[:4])\n    input2 := u32(input[4:])\n    b4(g.f(key32+input1)^input2, g.enc[:4])\n    copy(g.enc[4:], input[:4])\n}\n\nfunc main() {\n    input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}\n    key := []byte{0xF9, 0x04, 0xC1, 0xE2}\n\n    g := newGost(&cbrf)\n    g.mainStep(input, key)\n    for _, b := range g.enc {\n        fmt.Printf(\"[%02x]\", b)\n    }\n    fmt.Println()\n}\n", "C": "static unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n"}
{"id": 45531, "name": "State name puzzle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n)\n\nvar states = []string{\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n    \"California\", \"Colorado\", \"Connecticut\",\n    \"Delaware\",\n    \"Florida\", \"Georgia\", \"Hawaii\",\n    \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n    \"Kansas\", \"Kentucky\", \"Louisiana\",\n    \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n    \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n    \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n    \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n    \"Ohio\", \"Oklahoma\", \"Oregon\",\n    \"Pennsylvania\", \"Rhode Island\",\n    \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n    \"Utah\", \"Vermont\", \"Virginia\",\n    \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"}\n\nfunc main() {\n    play(states)\n    play(append(states,\n        \"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"))\n}\n\nfunc play(states []string) {\n    fmt.Println(len(states), \"states:\")\n    \n    set := make(map[string]bool, len(states))\n    for _, s := range states {\n        set[s] = true\n    }\n    \n    s := make([]string, len(set))\n    h := make([][26]byte, len(set))\n    var i int\n    for us := range set {\n        s[i] = us\n        for _, c := range us {\n            if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {\n                h[i][u]++\n            }\n        }\n        i++\n    }\n    \n    \n    type pair struct {\n        i1, i2 int\n    }\n    m := make(map[string][]pair)\n    b := make([]byte, 26) \n    for i1, h1 := range h {\n        for i2 := i1 + 1; i2 < len(h); i2++ {\n            \n            for i := range b {\n                b[i] = h1[i] + h[i2][i]\n            }\n            k := string(b) \n            \n            \n            \n            for _, x := range m[k] {\n                if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {\n                    fmt.Printf(\"%s, %s = %s, %s\\n\", s[i1], s[i2],\n                        s[x.i1], s[x.i2])\n                }\n            }\n            \n            m[k] = append(m[k], pair{i1, i2})\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define USE_FAKES 1\n\nconst char *states[] = {\n#if USE_FAKES\n\t\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\",\n#endif\n\t\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\"California\", \"Colorado\", \"Connecticut\",\n\t\"Delaware\",    \n\t\"Florida\", \"Georgia\", \"Hawaii\",\n\t\"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\t\"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\"Ohio\", \"Oklahoma\", \"Oregon\",\n\t\"Pennsylvania\", \"Rhode Island\",\n\t\"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\"Utah\", \"Vermont\", \"Virginia\",\n\t\"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n};\n\nint n_states = sizeof(states)/sizeof(*states);\ntypedef struct { unsigned char c[26]; const char *name[2]; } letters;\n\nvoid count_letters(letters *l, const char *s)\n{\n\tint c;\n\tif (!l->name[0]) l->name[0] = s;\n\telse l->name[1] = s;\n\n\twhile ((c = *s++)) {\n\t\tif (c >= 'a' && c <= 'z') l->c[c - 'a']++;\n\t\tif (c >= 'A' && c <= 'Z') l->c[c - 'A']++;\n\t}\n}\n\nint lcmp(const void *aa, const void *bb)\n{\n\tint i;\n\tconst letters *a = aa, *b = bb;\n\tfor (i = 0; i < 26; i++)\n\t\tif      (a->c[i] > b->c[i]) return  1;\n\t\telse if (a->c[i] < b->c[i]) return -1;\n\treturn 0;\n}\n\nint scmp(const void *a, const void *b)\n{\n\treturn strcmp(*(const char *const *)a, *(const char *const *)b);\n}\n\nvoid no_dup()\n{\n\tint i, j;\n\n\tqsort(states, n_states, sizeof(const char*), scmp);\n\n\tfor (i = j = 0; i < n_states;) {\n\t\twhile (++i < n_states && !strcmp(states[i], states[j]));\n\t\tif (i < n_states) states[++j] = states[i];\n\t}\n\n\tn_states = j + 1;\n}\n\nvoid find_mix()\n{\n\tint i, j, n;\n\tletters *l, *p;\n\n\tno_dup();\n\tn = n_states * (n_states - 1) / 2;\n\tp = l = calloc(n, sizeof(letters));\n\n\tfor (i = 0; i < n_states; i++)\n\t\tfor (j = i + 1; j < n_states; j++, p++) {\n\t\t\tcount_letters(p, states[i]);\n\t\t\tcount_letters(p, states[j]);\n\t\t}\n\n\tqsort(l, n, sizeof(letters), lcmp);\n\n\tfor (j = 0; j < n; j++) {\n\t\tfor (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {\n\t\t\tif (l[j].name[0] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[0]\n\t\t\t\t|| l[j].name[1] == l[i].name[1])\n\t\t\t\tcontinue;\n\t\t\tprintf(\"%s + %s => %s + %s\\n\",\n\t\t\t\tl[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);\n\t\t}\n\t}\n\tfree(l);\n}\n\nint main(void)\n{\n\tfind_mix();\n\treturn 0;\n}\n"}
{"id": 45532, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 45533, "name": "CRC-32", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"hash/crc32\"\n)\n\nfunc main() {\n    s := []byte(\"The quick brown fox jumps over the lazy dog\")\n    result := crc32.ChecksumIEEE(s)\n    fmt.Printf(\"%X\\n\", result)\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <zlib.h>\n \nint main()\n{\n\tconst char *s = \"The quick brown fox jumps over the lazy dog\";\n\tprintf(\"%lX\\n\", crc32(0, (const void*)s, strlen(s)));\n\n\treturn 0;\n}\n"}
{"id": 45534, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 45535, "name": "CSV to HTML translation", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"encoding/csv\"\n    \"fmt\"\n    \"html/template\"\n    \"strings\"\n)\n\nvar c = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n    if h, err := csvToHtml(c); err != nil {\n        fmt.Println(err)\n    } else {\n        fmt.Print(h)\n    }\n}\n\nfunc csvToHtml(c string) (string, error) {\n    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()\n    if err != nil {\n        return \"\", err\n    }\n    var b strings.Builder\n    err = template.Must(template.New(\"\").Parse(`<table>\n{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>\n{{end}}</table>\n`)).Execute(&b, data)\n    return b.String(), err\n}\n", "C": "#include <stdio.h>\n\nconst char *input = \n\t\"Character,Speech\\n\"\n\t\"The multitude,The messiah! Show us the messiah!\\n\"\n\t\"Brians mother,<angry>Now you listen here! He's not the messiah; \"\n\t\t\"he's a very naughty boy! Now go away!</angry>\\n\"\n\t\"The multitude,Who are you?\\n\"\n\t\"Brians mother,I'm his mother; that's who!\\n\"\n\t\"The multitude,Behold his mother! Behold his mother!\";\n\nint main()\n{\n\tconst char *s;\n\tprintf(\"<table>\\n<tr><td>\");\n\tfor (s = input; *s; s++) {\n\t\tswitch(*s) {\n\t\tcase '\\n': printf(\"</td></tr>\\n<tr><td>\"); break;\n\t\tcase ',':  printf(\"</td><td>\"); break;\n\t\tcase '<':  printf(\"&lt;\"); break;\n\t\tcase '>':  printf(\"&gt;\"); break;\n\t\tcase '&':  printf(\"&amp;\"); break;\n\t\tdefault:   putchar(*s);\n\t\t}\n\t}\n\tputs(\"</td></tr>\\n</table>\");\n\n\treturn 0;\n}\n"}
{"id": 45536, "name": "Classes", "Go": "package main\n\nimport \"fmt\"\n\n\n\n\ntype picnicBasket struct {\n    nServings int \n    corkscrew bool\n}\n\n\nfunc (b *picnicBasket) happy() bool {\n    return b.nServings > 1 && b.corkscrew\n}\n\n\n\n\n\n\n\n\n\nfunc newPicnicBasket(nPeople int) *picnicBasket {\n    \n    \n    \n    \n    return &picnicBasket{nPeople, nPeople > 0}\n}\n\n\nfunc main() {\n    var pb picnicBasket          \n    pbl := picnicBasket{}        \n    pbp := &picnicBasket{}       \n    pbn := new(picnicBasket)     \n    forTwo := newPicnicBasket(2) \n    \n    forToo := &picnicBasket{nServings: 2, corkscrew: true}\n\n    fmt.Println(pb.nServings, pb.corkscrew)\n    fmt.Println(pbl.nServings, pbl.corkscrew)\n    fmt.Println(pbp)\n    fmt.Println(pbn)\n    fmt.Println(forTwo)\n    fmt.Println(forToo)\n}\n", "C": "#include <stdlib.h>\n\ntypedef struct sMyClass\n{\n  int variable;\n} *MyClass;\n\nMyClass  MyClass_new()\n{\n  MyClass pthis = malloc(sizeof *pthis);\n  pthis->variable = 0;\n  return pthis;\n}\n\nvoid MyClass_delete(MyClass* pthis)\n{\n  if (pthis)\n  {\n    free(*pthis);\n    *pthis = NULL;\n  }\n}\n\nvoid MyClass_someMethod(MyClass pthis)\n{\n  pthis->variable = 1;\n}\n\nMyClass obj = MyClass_new();\nMyClass_someMethod(obj);\nMyClass_delete(&obj);\n"}
{"id": 45537, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 45538, "name": "Kaprekar numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n    order := 0\n    if n == 1 {\n        return true, -1\n    }\n\n    nn, power := n*n, uint64(1)\n    for power <= nn {\n        power *= base\n        order++\n    }\n\n    power /= base\n    order--\n    for ; power > 1; power /= base {\n        q, r := nn/power, nn%power\n        if q >= n {\n            return false, -1\n        }\n\n        if q+r == n {\n            return true, order\n        }\n\n        order--\n    }\n\n    return false, -1\n}\n\nfunc main() {\n    max := uint64(10000)\n    fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            fmt.Println(\"  \", m)\n        }\n    }\n\n    \n    max = 1e6\n    var count int\n    for m := uint64(0); m < max; m++ {\n        if is, _ := kaprekar(m, 10); is {\n            count++\n        }\n    }\n    fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n    \n    const base = 17\n    maxB := \"1000000\"\n    fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n    max, _ = strconv.ParseUint(maxB, base, 64)\n    fmt.Printf(\"\\n Base 10  Base %d        Square       Split\\n\", base)\n    for m := uint64(2); m < max; m++ {\n        is, pos := kaprekar(m, base)\n        if !is {\n            continue\n        }\n        sq := strconv.FormatUint(m*m, base)\n        str := strconv.FormatUint(m, base)\n        split := len(sq)-pos\n        fmt.Printf(\"%8d  %7s  %12s  %6s + %s\\n\", m,\n            str, sq, sq[:split], sq[split:]) \n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\ntypedef uint64_t ulong;\n\nint kaprekar(ulong n, int base)\n{\n\tulong nn = n * n, r, tens = 1;\n\n\tif ((nn - n) % (base - 1)) return 0;\n\n\twhile (tens < n) tens *= base;\n\tif (n == tens) return 1 == n;\n\n\twhile ((r = nn % tens) < n) {\n\t\tif (nn / tens + r == n) return tens;\n\t\ttens *= base;\n\t}\n\n\treturn 0;\n}\n\nvoid print_num(ulong n, int base)\n{\n\tulong q, div = base;\n\n\twhile (div < n) div *= base;\n\twhile (n && (div /= base)) {\n\t\tq = n / div;\n\t\tif (q < 10)     putchar(q + '0');\n\t\telse            putchar(q + 'a' - 10);\n\t\tn -= q * div;\n\t}\n}\n\nint main()\n{\n\tulong i, tens;\n\tint cnt = 0;\n\tint base = 10;\n\n\tprintf(\"base 10:\\n\");\n\tfor (i = 1; i < 1000000; i++)\n\t\tif (kaprekar(i, base))\n\t\t\tprintf(\"%3d: %llu\\n\", ++cnt, i);\n\n\tbase = 17;\n\tprintf(\"\\nbase %d:\\n  1: 1\\n\", base);\n\tfor (i = 2, cnt = 1; i < 1000000; i++)\n\t\tif ((tens = kaprekar(i, base))) {\n\t\t\tprintf(\"%3d: %llu\", ++cnt, i);\n\t\t\tprintf(\" \\t\"); print_num(i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i, base);\n\t\t\tprintf(\"\\t\");  print_num(i * i / tens, base);\n\t\t\tprintf(\" + \"); print_num(i * i % tens, base);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\treturn 0;\n}\n"}
{"id": 45539, "name": "LZW compression", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\nfunc compress(uncompressed string) []int {\n\t\n\tdictSize := 256\n\t\n\t\n\tdictionary := make(map[string]int, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\t\n\t\t\n\t\tdictionary[string([]byte{byte(i)})] = i\n\t}\n\n\tvar result []int\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tc := uncompressed[i]\n\t\twc := append(w, c)\n\t\tif _, ok := dictionary[string(wc)]; ok {\n\t\t\tw = wc\n\t\t} else {\n\t\t\tresult = append(result, dictionary[string(w)])\n\t\t\t\n\t\t\tdictionary[string(wc)] = dictSize\n\t\t\tdictSize++\n\t\t\t\n\t\t\twc[0] = c\n\t\t\tw = wc[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t\n\t\tresult = append(result, dictionary[string(w)])\n\t}\n\treturn result\n}\n\ntype BadSymbolError int\n\nfunc (e BadSymbolError) Error() string {\n\treturn fmt.Sprint(\"Bad compressed symbol \", int(e))\n}\n\n\nfunc decompress(compressed []int) (string, error) {\n\t\n\tdictSize := 256\n\tdictionary := make(map[int][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[i] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar w []byte\n\tfor _, k := range compressed {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\t\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if k == dictSize && len(w) > 0 {\n\t\t\tentry = append(w, w[0])\n\t\t} else {\n\t\t\treturn result.String(), BadSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(w) > 0 {\n\t\t\t\n\t\t\tw = append(w, entry[0])\n\t\t\tdictionary[dictSize] = w\n\t\t\tdictSize++\n\t\t}\n\t\tw = entry\n\t}\n\treturn result.String(), nil\n}\n\nfunc main() {\n\tcompressed := compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\tfmt.Println(compressed)\n\tdecompressed, err := decompress(compressed)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(decompressed)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\nvoid* mem_alloc(size_t item_size, size_t n_item)\n{\n  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);\n  x[0] = item_size;\n  x[1] = n_item;\n  return x + 2;\n}\n\nvoid* mem_extend(void *m, size_t new_n)\n{\n  size_t *x = (size_t*)m - 2;\n  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);\n  if (new_n > x[1])\n    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));\n  x[1] = new_n;\n  return x + 2;\n}\n\ninline void _clear(void *m)\n{\n  size_t *x = (size_t*)m - 2;\n  memset(m, 0, x[0] * x[1]);\n}\n\n#define _new(type, n) mem_alloc(sizeof(type), n)\n#define _del(m)   { free((size_t*)(m) - 2); m = 0; }\n#define _len(m)   *((size_t*)m - 1)\n#define _setsize(m, n)  m = mem_extend(m, n)\n#define _extend(m)  m = mem_extend(m, _len(m) * 2)\n\n\n\ntypedef uint8_t byte;\ntypedef uint16_t ushort;\n\n#define M_CLR 256 \n#define M_EOD 257 \n#define M_NEW 258 \n\n\ntypedef struct {\n  ushort next[256];\n} lzw_enc_t;\n\n\ntypedef struct {\n  ushort prev, back;\n  byte c;\n} lzw_dec_t;\n\nbyte* lzw_encode(byte *in, int max_bits)\n{\n  int len = _len(in), bits = 9, next_shift = 512;\n  ushort code, c, nc, next_code = M_NEW;\n  lzw_enc_t *d = _new(lzw_enc_t, 512);\n\n  if (max_bits > 15) max_bits = 15;\n  if (max_bits < 9 ) max_bits = 12;\n\n  byte *out = _new(ushort, 4);\n  int out_len = 0, o_bits = 0;\n  uint32_t tmp = 0;\n\n  inline void write_bits(ushort x) {\n    tmp = (tmp << bits) | x;\n    o_bits += bits;\n    if (_len(out) <= out_len) _extend(out);\n    while (o_bits >= 8) {\n      o_bits -= 8;\n      out[out_len++] = tmp >> o_bits;\n      tmp &= (1 << o_bits) - 1;\n    }\n  }\n\n  \n  for (code = *(in++); --len; ) {\n    c = *(in++);\n    if ((nc = d[code].next[c]))\n      code = nc;\n    else {\n      write_bits(code);\n      nc = d[code].next[c] = next_code++;\n      code = c;\n    }\n\n    \n    if (next_code == next_shift) {\n      \n      if (++bits > max_bits) {\n        \n        write_bits(M_CLR);\n\n        bits = 9;\n        next_shift = 512;\n        next_code = M_NEW;\n        _clear(d);\n      } else  \n        _setsize(d, next_shift *= 2);\n    }\n  }\n\n  write_bits(code);\n  write_bits(M_EOD);\n  if (tmp) write_bits(tmp);\n\n  _del(d);\n\n  _setsize(out, out_len);\n  return out;\n}\n\nbyte* lzw_decode(byte *in)\n{\n  byte *out = _new(byte, 4);\n  int out_len = 0;\n\n  inline void write_out(byte c)\n  {\n    while (out_len >= _len(out)) _extend(out);\n    out[out_len++] = c;\n  }\n\n  lzw_dec_t *d = _new(lzw_dec_t, 512);\n  int len, j, next_shift = 512, bits = 9, n_bits = 0;\n  ushort code, c, t, next_code = M_NEW;\n\n  uint32_t tmp = 0;\n  inline void get_code() {\n    while(n_bits < bits) {\n      if (len > 0) {\n        len --;\n        tmp = (tmp << 8) | *(in++);\n        n_bits += 8;\n      } else {\n        tmp = tmp << (bits - n_bits);\n        n_bits = bits;\n      }\n    }\n    n_bits -= bits;\n    code = tmp >> n_bits;\n    tmp &= (1 << n_bits) - 1;\n  }\n\n  inline void clear_table() {\n    _clear(d);\n    for (j = 0; j < 256; j++) d[j].c = j;\n    next_code = M_NEW;\n    next_shift = 512;\n    bits = 9;\n  };\n\n  clear_table(); \n  for (len = _len(in); len;) {\n    get_code();\n    if (code == M_EOD) break;\n    if (code == M_CLR) {\n      clear_table();\n      continue;\n    }\n\n    if (code >= next_code) {\n      fprintf(stderr, \"Bad sequence\\n\");\n      _del(out);\n      goto bail;\n    }\n\n    d[next_code].prev = c = code;\n    while (c > 255) {\n      t = d[c].prev; d[t].back = c; c = t;\n    }\n\n    d[next_code - 1].c = c;\n\n    while (d[c].back) {\n      write_out(d[c].c);\n      t = d[c].back; d[c].back = 0; c = t;\n    }\n    write_out(d[c].c);\n\n    if (++next_code >= next_shift) {\n      if (++bits > 16) {\n        \n        fprintf(stderr, \"Too many bits\\n\");\n        _del(out);\n        goto bail;\n      }\n      _setsize(d, next_shift *= 2);\n    }\n  }\n\n  \n  if (code != M_EOD) fputs(\"Bits did not end in EOD\\n\", stderr);\n\n  _setsize(out, out_len);\nbail: _del(d);\n  return out;\n}\n\nint main()\n{\n  int i, fd = open(\"unixdict.txt\", O_RDONLY);\n\n  if (fd == -1) {\n    fprintf(stderr, \"Can't read file\\n\");\n    return 1;\n  };\n\n  struct stat st;\n  fstat(fd, &st);\n\n  byte *in = _new(char, st.st_size);\n  read(fd, in, st.st_size);\n  _setsize(in, st.st_size);\n  close(fd);\n\n  printf(\"input size:   %d\\n\", _len(in));\n\n  byte *enc = lzw_encode(in, 9);\n  printf(\"encoded size: %d\\n\", _len(enc));\n\n  byte *dec = lzw_decode(enc);\n  printf(\"decoded size: %d\\n\", _len(dec));\n\n  for (i = 0; i < _len(dec); i++)\n    if (dec[i] != in[i]) {\n      printf(\"bad decode at %d\\n\", i);\n      break;\n    }\n\n  if (i == _len(dec)) printf(\"Decoded ok\\n\");\n\n\n  _del(in);\n  _del(enc);\n  _del(dec);\n\n  return 0;\n}\n"}
{"id": 45540, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 45541, "name": "Hofstadter Figure-Figure sequences", "Go": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n\n\n\nfunc init() {\n    \n    r := []int{0, 1}\n    s := []int{0, 2}\n\n    ffr = func(n int) int {\n        for len(r) <= n {\n            nrk := len(r) - 1       \n            rNxt := r[nrk] + s[nrk] \n            r = append(r, rNxt)     \n            for sn := r[nrk] + 2; sn < rNxt; sn++ {\n                s = append(s, sn)   \n            }\n            s = append(s, rNxt+1)   \n        }\n        return r[n]\n    }\n\n    ffs = func(n int) int {\n        for len(s) <= n {\n            ffr(len(r))\n        }\n        return s[n]\n    }\n}\n\nfunc main() {\n    \n    for n := 1; n <= 10; n++ {\n        fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n    }\n    \n    var found [1001]int\n    for n := 1; n <= 40; n++ {\n        found[ffr(n)]++\n    }\n    for n := 1; n <= 960; n++ {\n        found[ffs(n)]++\n    }\n    for i := 1; i <= 1000; i++ {\n        if found[i] != 1 {\n            fmt.Println(\"task 4: FAIL\")\n            return\n        }\n    }\n    fmt.Println(\"task 4: PASS\")\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); \n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <=  40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}\n"}
{"id": 45542, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 45543, "name": "Magic squares of odd order", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n    M := func(x int) int { return (x + n - 1) % n }\n    if n <= 0 || n&1 == 0 {\n        n = 5\n        log.Println(\"forcing size\", n)\n    }\n    m := make([]int, n*n)\n    i, j := 0, n/2\n    for k := 1; k <= n*n; k++ {\n        m[i*n+j] = k\n        if m[M(i)*n+M(j)] != 0 {\n            i = (i + 1) % n\n        } else {\n            i, j = M(i), M(j)\n        }\n    }\n    return n, m\n}\n\nfunc main() {\n    n, m := ms(5)\n    i := 2\n    for j := 1; j <= n*n; j *= 10 {\n        i++\n    }\n    f := fmt.Sprintf(\"%%%dd\", i)\n    for i := 0; i < n; i++ {\n        for j := 0; j < n; j++ {\n            fmt.Printf(f, m[i*n+j])\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \nint f(int n, int x, int y)\n{\n\treturn (x + y*2 + 1)%n;\n}\n \nint main(int argc, char **argv)\n{\n\tint i, j, n;\n \n\t\n\tif(argc!=2) return 1;\n\n\t\n\tn = atoi(argv[1]);\n\tif (n < 3 || (n%2) == 0) return 2;\n \n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\"% 4d\", f(n, n - j - 1, i)*n + f(n, j, i) + 1);\n\t\tputchar('\\n');\n\t}\n\tprintf(\"\\n Magic Constant: %d.\\n\", (n*n+1)/2*n);\n \n\treturn 0;\n}\n"}
{"id": 45544, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 45545, "name": "Yellowstone sequence", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc yellowstone(n int) []int {\n    m := make(map[int]bool)\n    a := make([]int, n+1)\n    for i := 1; i < 4; i++ {\n        a[i] = i\n        m[i] = true\n    }\n    min := 4\n    for c := 4; c <= n; c++ {\n        for i := min; ; i++ {\n            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n                a[c] = i\n                m[i] = true\n                if i == min {\n                    min++\n                }\n                break\n            }\n        }\n    }    \n    return a[1:]\n}\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    x := make([]int, 100)\n    for i := 0; i < 100; i++ {\n        x[i] = i + 1\n    }\n    y := yellowstone(100)\n    fmt.Println(\"The first 30 Yellowstone numbers are:\")\n    fmt.Println(y[:30])\n    g := exec.Command(\"gnuplot\", \"-persist\")\n    w, err := g.StdinPipe()\n    check(err)\n    check(g.Start())\n    fmt.Fprintln(w, \"unset key; plot '-'\")\n    for i, xi := range x {\n        fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n    }\n    fmt.Fprintln(w, \"e\")\n    w.Close()\n    g.Wait()\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n    struct lnode_t *prev;\n    struct lnode_t *next;\n    int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n    Lnode *node = malloc(sizeof(Lnode));\n    if (node == NULL) {\n        return NULL;\n    }\n    node->v = v;\n    node->prev = NULL;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_lnode(Lnode *node) {\n    if (node == NULL) {\n        return;\n    }\n\n    node->v = 0;\n    node->prev = NULL;\n    free_lnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct list_t {\n    Lnode *front;\n    Lnode *back;\n    size_t len;\n} List;\n\nList *make_list() {\n    List *list = malloc(sizeof(List));\n    if (list == NULL) {\n        return NULL;\n    }\n    list->front = NULL;\n    list->back = NULL;\n    list->len = 0;\n    return list;\n}\n\nvoid free_list(List *list) {\n    if (list == NULL) {\n        return;\n    }\n    list->len = 0;\n    list->back = NULL;\n    free_lnode(list->front);\n    list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n    Lnode *node;\n\n    if (list == NULL) {\n        return;\n    }\n\n    node = make_list_node(v);\n    if (list->front == NULL) {\n        list->front = node;\n        list->back = node;\n        list->len = 1;\n    } else {\n        node->prev = list->back;\n        list->back->next = node;\n        list->back = node;\n        list->len++;\n    }\n}\n\nvoid list_print(List *list) {\n    Lnode *it;\n\n    if (list == NULL) {\n        return;\n    }\n\n    for (it = list->front; it != NULL; it = it->next) {\n        printf(\"%d \", it->v);\n    }\n}\n\nint list_get(List *list, int idx) {\n    Lnode *it = NULL;\n\n    if (list != NULL && list->front != NULL) {\n        int i;\n        if (idx < 0) {\n            it = list->back;\n            i = -1;\n            while (it != NULL && i > idx) {\n                it = it->prev;\n                i--;\n            }\n        } else {\n            it = list->front;\n            i = 0;\n            while (it != NULL && i < idx) {\n                it = it->next;\n                i++;\n            }\n        }\n    }\n\n    if (it == NULL) {\n        return INT_MIN;\n    }\n    return it->v;\n}\n\n\n\ntypedef struct mnode_t {\n    int k;\n    bool v;\n    struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n    Mnode *node = malloc(sizeof(Mnode));\n    if (node == NULL) {\n        return node;\n    }\n    node->k = k;\n    node->v = v;\n    node->next = NULL;\n    return node;\n}\n\nvoid free_mnode(Mnode *node) {\n    if (node == NULL) {\n        return;\n    }\n    node->k = 0;\n    node->v = false;\n    free_mnode(node->next);\n    node->next = NULL;\n}\n\ntypedef struct map_t {\n    Mnode *front;\n} Map;\n\nMap *make_map() {\n    Map *map = malloc(sizeof(Map));\n    if (map == NULL) {\n        return NULL;\n    }\n    map->front = NULL;\n    return map;\n}\n\nvoid free_map(Map *map) {\n    if (map == NULL) {\n        return;\n    }\n    free_mnode(map->front);\n    map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n    if (map == NULL) {\n        return;\n    }\n    if (map->front == NULL) {\n        map->front = make_map_node(k, v);\n    } else {\n        Mnode *it = map->front;\n        while (it->next != NULL) {\n            it = it->next;\n        }\n        it->next = make_map_node(k, v);\n    }\n}\n\nbool map_get(Map *map, int k) {\n    if (map != NULL) {\n        Mnode *it = map->front;\n        while (it != NULL && it->k != k) {\n            it = it->next;\n        }\n        if (it != NULL) {\n            return it->v;\n        }\n    }\n    return false;\n}\n\n\n\nint gcd(int u, int v) {\n    if (u < 0) u = -u;\n    if (v < 0) v = -v;\n    if (v) {\n        while ((u %= v) && (v %= u));\n    }\n    return u + v;\n}\n\nList *yellow(size_t n) {\n    List *a;\n    Map *b;\n    int i;\n\n    a = make_list();\n    list_insert(a, 1);\n    list_insert(a, 2);\n    list_insert(a, 3);\n\n    b = make_map();\n    map_insert(b, 1, true);\n    map_insert(b, 2, true);\n    map_insert(b, 3, true);\n\n    i = 4;\n\n    while (n > a->len) {\n        if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n            list_insert(a, i);\n            map_insert(b, i, true);\n            i = 4;\n        }\n        i++;\n    }\n\n    free_map(b);\n    return a;\n}\n\nint main() {\n    List *a = yellow(30);\n    list_print(a);\n    free_list(a);\n    putc('\\n', stdout);\n    return 0;\n}\n"}
{"id": 45546, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 45547, "name": "Cut a rectangle", "Go": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n    if y == 0 || y == h || x == 0 || x == w {\n        cnt += 2\n        return\n    }\n    t := y*(w+1) + x\n    grid[t]++\n    grid[last-t]++\n    for i, d := range dir {\n        if grid[t+next[i]] == 0 {\n            walk(y+d[0], x+d[1])\n        }\n    }\n    grid[t]--\n    grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n    h = hh\n    w = ww\n\n    if h&1 != 0 {\n        h, w = w, h\n    }\n    switch {\n    case h&1 == 1:\n        return 0\n    case w == 1:\n        return 1\n    case w == 2:\n        return h\n    case h == 2:\n        return w\n    }\n    cy := h / 2\n    cx := w / 2\n\n    grid = make([]byte, (h+1)*(w+1))\n    last = len(grid) - 1\n    next[0] = -1\n    next[1] = -w - 1\n    next[2] = 1\n    next[3] = w + 1\n\n    if recur != 0 {\n        cnt = 0\n    }\n    for x := cx + 1; x < w; x++ {\n        t := cy*(w+1) + x\n        grid[t] = 1\n        grid[last-t] = 1\n        walk(cy-1, x)\n    }\n    cnt++\n\n    if h == w {\n        cnt *= 2\n    } else if w&1 == 0 && recur != 0 {\n        solve(w, h, 0)\n    }\n    return cnt\n}\n\nfunc main() {\n    for y := 1; y <= 10; y++ {\n        for x := 1; x <= y; x++ {\n            if x&1 == 0 || y&1 == 0 {\n                fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n            }\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef unsigned char byte;\nbyte *grid = 0;\n\nint w, h, len;\nunsigned long long cnt;\n\nstatic int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\nvoid walk(int y, int x)\n{\n\tint i, t;\n\n\tif (!y || y == h || !x || x == w) {\n\t\tcnt += 2;\n\t\treturn;\n\t}\n\n\tt = y * (w + 1) + x;\n\tgrid[t]++, grid[len - t]++;\n\n\tfor (i = 0; i < 4; i++)\n\t\tif (!grid[t + next[i]])\n\t\t\twalk(y + dir[i][0], x + dir[i][1]);\n\n\tgrid[t]--, grid[len - t]--;\n}\n\nunsigned long long solve(int hh, int ww, int recur)\n{\n\tint t, cx, cy, x;\n\n\th = hh, w = ww;\n\n\tif (h & 1) t = w, w = h, h = t;\n\tif (h & 1) return 0;\n\tif (w == 1) return 1;\n\tif (w == 2) return h;\n\tif (h == 2) return w;\n\n\tcy = h / 2, cx = w / 2;\n\n\tlen = (h + 1) * (w + 1);\n\tgrid = realloc(grid, len);\n\tmemset(grid, 0, len--);\n\n\tnext[0] = -1;\n\tnext[1] = -w - 1;\n\tnext[2] = 1;\n\tnext[3] = w + 1;\n\n\tif (recur) cnt = 0;\n\tfor (x = cx + 1; x < w; x++) {\n\t\tt = cy * (w + 1) + x;\n\t\tgrid[t] = 1;\n\t\tgrid[len - t] = 1;\n\t\twalk(cy - 1, x);\n\t}\n\tcnt++;\n\n\tif (h == w)\n\t\tcnt *= 2;\n\telse if (!(w & 1) && recur)\n\t\tsolve(w, h, 0);\n\n\treturn cnt;\n}\n\nint main()\n{\n\tint y, x;\n\tfor (y = 1; y <= 10; y++)\n\t\tfor (x = 1; x <= y; x++)\n\t\t\tif (!(x & 1) || !(y & 1))\n\t\t\t\tprintf(\"%d x %d: %llu\\n\", y, x, solve(y, x, 1));\n\n\treturn 0;\n}\n"}
{"id": 45548, "name": "Mertens function", "Go": "package main\n\nimport \"fmt\"\n\nfunc mertens(to int) ([]int, int, int) {\n    if to < 1 {\n        to = 1\n    }\n    merts := make([]int, to+1)\n    primes := []int{2}\n    var sum, zeros, crosses int\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                sum++\n            } else {\n                sum--\n            }\n        }\n        merts[i] = sum\n        if sum == 0 {\n            zeros++\n            if i > 1 && merts[i-1] != 0 {\n                crosses++\n            }\n        }\n    }\n    return merts, zeros, crosses\n}\n\nfunc main() {\n    merts, zeros, crosses := mertens(1000)\n    fmt.Println(\"Mertens sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", merts[i])\n    }\n    fmt.Println(\"\\n\\nEquals zero\", zeros, \"times between 1 and 1000\")\n    fmt.Println(\"\\nCrosses zero\", crosses, \"times between 1 and 1000\")\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint* mertens_numbers(int max) {\n    int* m = malloc((max + 1) * sizeof(int));\n    if (m == NULL)\n        return m;\n    m[1] = 1;\n    for (int n = 2; n <= max; ++n) {\n        m[n] = 1;\n        for (int k = 2; k <= n; ++k)\n            m[n] -= m[n/k];\n    }\n    return m;\n}\n\nint main() {\n    const int max = 1000;\n    int* mertens = mertens_numbers(max);\n    if (mertens == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 199 Mertens numbers:\\n\");\n    const int count = 200;\n    for (int i = 0, column = 0; i < count; ++i) {\n        if (column > 0)\n            printf(\" \");\n        if (i == 0)\n            printf(\"  \");\n        else\n            printf(\"%2d\", mertens[i]);\n        ++column;\n        if (column == 20) {\n            printf(\"\\n\");\n            column = 0;\n        }\n    }\n    int zero = 0, cross = 0, previous = 0;\n    for (int i = 1; i <= max; ++i) {\n        int m = mertens[i];\n        if (m == 0) {\n            ++zero;\n            if (previous != 0)\n                ++cross;\n        }\n        previous = m;\n    }\n    free(mertens);\n    printf(\"M(n) is zero %d times for 1 <= n <= %d.\\n\", zero, max);\n    printf(\"M(n) crosses zero %d times for 1 <= n <= %d.\\n\", cross, max);\n    return 0;\n}\n"}
{"id": 45549, "name": "Order by pair comparisons", "Go": "package main\n \nimport (\n    \"fmt\"\n    \"sort\"\n    \"strings\"\n)\n\nvar count int = 0\n\nfunc interactiveCompare(s1, s2 string) bool {\n    count++\n    fmt.Printf(\"(%d) Is %s < %s? \", count, s1, s2)\n    var response string\n    _, err := fmt.Scanln(&response)\n    return err == nil && strings.HasPrefix(response, \"y\")\n}\n\nfunc main() {\n    items := []string{\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"}\n    \n    var sortedItems []string\n    \n    \n    \n    for _, item := range items {\n        fmt.Printf(\"Inserting '%s' into %s\\n\", item, sortedItems)\n        \n        \n        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {\n            return interactiveCompare(item, sortedItems[i])\n        })\n        sortedItems = append(sortedItems[:spotToInsert],\n                             append([]string{item}, sortedItems[spotToInsert:]...)...)\n    }\n    fmt.Println(sortedItems)\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint interactiveCompare(const void *x1, const void *x2)\n{\n  const char *s1 = *(const char * const *)x1;\n  const char *s2 = *(const char * const *)x2;\n  static int count = 0;\n  printf(\"(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: \", ++count, s1, s2);\n  int response;\n  scanf(\"%d\", &response);\n  return response;\n}\n\nvoid printOrder(const char *items[], int len)\n{\n  printf(\"{ \");\n  for (int i = 0; i < len; ++i) printf(\"%s \", items[i]);\n  printf(\"}\\n\");\n}\n\nint main(void)\n{\n  const char *items[] =\n    {\n      \"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"\n    };\n\n  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);\n  printOrder(items, sizeof(items)/sizeof(*items));\n  return 0;\n}\n"}
{"id": 45550, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45551, "name": "Benford's law", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc Fib1000() []float64 {\n    a, b, r := 0., 1., [1000]float64{}\n    for i := range r {\n        r[i], a, b = b, b, b+a\n    }\n    return r[:]\n}\n\nfunc main() {\n    show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n    var f [9]int\n    for _, v := range c {\n        f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n    }\n    fmt.Println(title)\n    fmt.Println(\"Digit  Observed  Predicted\")\n    for i, n := range f {\n        fmt.Printf(\"  %d  %9.3f  %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n            math.Log10(1+1/float64(i+1)))\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat *benford_distribution(void)\n{\n    static float prob[9];\n    for (int i = 1; i < 10; i++)\n        prob[i - 1] = log10f(1 + 1.0 / i);\n\n    return prob;\n}\n\nfloat *get_actual_distribution(char *fn)\n{\n    FILE *input = fopen(fn, \"r\");\n    if (!input)\n    {\n        perror(\"Can't open file\");\n        exit(EXIT_FAILURE);\n    }\n\n    int tally[9] = { 0 };\n    char c;\n    int total = 0;\n    while ((c = getc(input)) != EOF)\n    {\n        \n        while (c < '1' || c > '9')\n            c = getc(input);\n\n        tally[c - '1']++;\n        total++;\n\n        \n        while ((c = getc(input)) != '\\n' && c != EOF)\n            ;\n    }\n    fclose(input);\n    \n    static float freq[9];\n    for (int i = 0; i < 9; i++)\n        freq[i] = tally[i] / (float) total;\n\n    return freq;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        printf(\"Usage: benford <file>\\n\");\n        return EXIT_FAILURE;\n    }\n\n    float *actual = get_actual_distribution(argv[1]);\n    float *expected = benford_distribution();  \n\n    puts(\"digit\\tactual\\texpected\");\n    for (int i = 0; i < 9; i++)\n        printf(\"%d\\t%.3f\\t%.3f\\n\", i + 1, actual[i], expected[i]);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45552, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 45553, "name": "Nautical bell", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    watches := []string{\n        \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n        \"Afternoon\", \"Dog\", \"First\",\n    }\n    for {\n        t := time.Now()\n        h := t.Hour()\n        m := t.Minute()\n        s := t.Second()\n        if (m == 0 || m == 30) && s == 0 {\n            bell := 0\n            if m == 30 {\n                bell = 1\n            }\n            bells := (h*2 + bell) % 8\n            watch := h/4 + 1\n            if bells == 0 {\n                bells = 8\n                watch--\n            }\n            sound := strings.Repeat(\"\\a\", bells)\n            pl := \"s\"\n            if bells == 1 {\n                pl = \" \"\n            }\n            w := watches[watch] + \" watch\"\n            if watch == 5 {\n                if bells < 5 {\n                    w = \"First \" + w\n                } else {\n                    w = \"Last \" + w\n                }\n            }\n            fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n        }\n        time.Sleep(1 * time.Second)\n    }\n}\n", "C": "#include<unistd.h>\n#include<stdio.h>\n#include<time.h>\n\n#define SHORTLAG 1000\n#define LONGLAG  2000\n\nint main(){\n\tint i,times,hour,min,sec,min1,min2;\n\t\n\ttime_t t;\n\tstruct tm* currentTime;\n\t\n\twhile(1){\n\t\ttime(&t);\n\t\tcurrentTime = localtime(&t);\n\t\t\n\t\thour = currentTime->tm_hour;\n\t\tmin = currentTime->tm_min;\n\t\tsec = currentTime->tm_sec;\n\t\t\n\t\thour = 12;\n\t\tmin = 0;\n\t\tsec = 0;\n\t\t\n\t\tif((min==0 || min==30) && sec==0)\n\t\t\ttimes = ((hour*60 + min)%240)%8;\n\t\tif(times==0){\n\t\t\ttimes = 8;\n\t\t}\t\n\n\t\tif(min==0){\n\t\t\tmin1 = 0;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\telse{\n\t\t\tmin1 = 3;\n\t\t\tmin2 = 0;\n\t\t}\n\t\t\n\t\tif((min==0 || min==30) && sec==0){\n\t\t\tprintf(\"\\nIt is now %d:%d%d %s. Sounding the bell %d times.\",hour,min1,min2,(hour>11)?\"PM\":\"AM\",times);\n\t\t\n\t\t\tfor(i=1;i<=times;i++){\n\t\t\t\tprintf(\"\\a\");\n\t\t\t\t\n\t\t\t\t(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 45554, "name": "Anonymous recursion", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {\n        f, ok := arFib(n)\n        if ok {\n            fmt.Printf(\"fib %d = %d\\n\", n, f)\n        } else {\n            fmt.Println(\"fib undefined for negative numbers\")\n        }\n    }\n}\n\nfunc arFib(n int) (int, bool) {\n    switch {\n    case n < 0:\n        return 0, false\n    case n < 2:\n        return n, true\n    }\n    return yc(func(recurse fn) fn {\n        return func(left, term1, term2 int) int {\n            if left == 0 {\n                return term1+term2\n            }\n            return recurse(left-1, term1+term2, term1)\n        }\n    })(n-2, 1, 0), true\n}\n\ntype fn func(int, int, int) int\ntype ff func(fn) fn\ntype fx func(fx) fn\n\nfunc yc(f ff) fn {\n    return func(x fx) fn {\n        return x(x)\n    }(func(x fx) fn {\n        return f(func(a1, a2, a3 int) int {\n            return x(x)(a1, a2, a3)\n        })\n    })\n}\n", "C": "#include <stdio.h>\n\nlong fib(long x)\n{\n        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };\n        if (x < 0) {\n                printf(\"Bad argument: fib(%ld)\\n\", x);\n                return -1;\n        }\n        return fib_i(x);\n}\n\nlong fib_i(long n) \n{\n        printf(\"This is not the fib you are looking for\\n\");\n        return -1;\n}\n\nint main()\n{\n        long x;\n        for (x = -1; x < 4; x ++)\n                printf(\"fib %ld = %ld\\n\", x, fib(x));\n\n        printf(\"calling fib_i from outside fib:\\n\");\n        fib_i(3);\n\n        return 0;\n}\n"}
{"id": 45555, "name": "Snake", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"time\"\n\n\ttermbox \"github.com/nsf/termbox-go\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano())\n\tscore, err := playSnake()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Final score:\", score)\n}\n\ntype snake struct {\n\tbody          []position \n\theading       direction\n\twidth, height int\n\tcells         []termbox.Cell\n}\n\ntype position struct {\n\tX int\n\tY int\n}\n\ntype direction int\n\nconst (\n\tNorth direction = iota\n\tEast\n\tSouth\n\tWest\n)\n\nfunc (p position) next(d direction) position {\n\tswitch d {\n\tcase North:\n\t\tp.Y--\n\tcase East:\n\t\tp.X++\n\tcase South:\n\t\tp.Y++\n\tcase West:\n\t\tp.X--\n\t}\n\treturn p\n}\n\nfunc playSnake() (int, error) {\n\terr := termbox.Init()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer termbox.Close()\n\n\ttermbox.Clear(fg, bg)\n\ttermbox.HideCursor()\n\ts := &snake{\n\t\t\n\t\t\n\t\tbody:  make([]position, 0, 32),\n\t\tcells: termbox.CellBuffer(),\n\t}\n\ts.width, s.height = termbox.Size()\n\ts.drawBorder()\n\ts.startSnake()\n\ts.placeFood()\n\ts.flush()\n\n\tmoveCh, errCh := s.startEventLoop()\n\tconst delay = 125 * time.Millisecond\n\tfor t := time.NewTimer(delay); ; t.Reset(delay) {\n\t\tvar move direction\n\t\tselect {\n\t\tcase err = <-errCh:\n\t\t\treturn len(s.body), err\n\t\tcase move = <-moveCh:\n\t\t\tif !t.Stop() {\n\t\t\t\t<-t.C \n\t\t\t}\n\t\tcase <-t.C:\n\t\t\tmove = s.heading\n\t\t}\n\t\tif s.doMove(move) {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn len(s.body), err\n}\n\nfunc (s *snake) startEventLoop() (<-chan direction, <-chan error) {\n\tmoveCh := make(chan direction)\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(errCh)\n\t\tfor {\n\t\t\tswitch ev := termbox.PollEvent(); ev.Type {\n\t\t\tcase termbox.EventKey:\n\t\t\t\tswitch ev.Ch { \n\t\t\t\tcase 'w', 'W', 'k', 'K':\n\t\t\t\t\tmoveCh <- North\n\t\t\t\tcase 'a', 'A', 'h', 'H':\n\t\t\t\t\tmoveCh <- West\n\t\t\t\tcase 's', 'S', 'j', 'J':\n\t\t\t\t\tmoveCh <- South\n\t\t\t\tcase 'd', 'D', 'l', 'L':\n\t\t\t\t\tmoveCh <- East\n\t\t\t\tcase 0:\n\t\t\t\t\tswitch ev.Key { \n\t\t\t\t\tcase termbox.KeyArrowUp:\n\t\t\t\t\t\tmoveCh <- North\n\t\t\t\t\tcase termbox.KeyArrowDown:\n\t\t\t\t\t\tmoveCh <- South\n\t\t\t\t\tcase termbox.KeyArrowLeft:\n\t\t\t\t\t\tmoveCh <- West\n\t\t\t\t\tcase termbox.KeyArrowRight:\n\t\t\t\t\t\tmoveCh <- East\n\t\t\t\t\tcase termbox.KeyEsc: \n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase termbox.EventResize:\n\t\t\t\t\n\t\t\t\terrCh <- errors.New(\"terminal resizing unsupported\")\n\t\t\t\treturn\n\t\t\tcase termbox.EventError:\n\t\t\t\terrCh <- ev.Err\n\t\t\t\treturn\n\t\t\tcase termbox.EventInterrupt:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn moveCh, errCh\n}\n\nfunc (s *snake) flush() {\n\ttermbox.Flush()\n\ts.cells = termbox.CellBuffer()\n}\n\nfunc (s *snake) getCellRune(p position) rune {\n\ti := p.Y*s.width + p.X\n\treturn s.cells[i].Ch\n}\nfunc (s *snake) setCell(p position, c termbox.Cell) {\n\ti := p.Y*s.width + p.X\n\ts.cells[i] = c\n}\n\nfunc (s *snake) drawBorder() {\n\tfor x := 0; x < s.width; x++ {\n\t\ts.setCell(position{x, 0}, border)\n\t\ts.setCell(position{x, s.height - 1}, border)\n\t}\n\tfor y := 0; y < s.height-1; y++ {\n\t\ts.setCell(position{0, y}, border)\n\t\ts.setCell(position{s.width - 1, y}, border)\n\t}\n}\n\nfunc (s *snake) placeFood() {\n\tfor {\n\t\t\n\t\tx := rand.Intn(s.width-2) + 1\n\t\ty := rand.Intn(s.height-2) + 1\n\t\tfoodp := position{x, y}\n\t\tr := s.getCellRune(foodp)\n\t\tif r != ' ' {\n\t\t\tcontinue\n\t\t}\n\t\ts.setCell(foodp, food)\n\t\treturn\n\t}\n}\n\nfunc (s *snake) startSnake() {\n\t\n\tx := rand.Intn(s.width/2) + s.width/4\n\ty := rand.Intn(s.height/2) + s.height/4\n\thead := position{x, y}\n\ts.setCell(head, snakeHead)\n\ts.body = append(s.body[:0], head)\n\ts.heading = direction(rand.Intn(4))\n}\n\nfunc (s *snake) doMove(move direction) bool {\n\thead := s.body[len(s.body)-1]\n\ts.setCell(head, snakeBody)\n\thead = head.next(move)\n\ts.heading = move\n\ts.body = append(s.body, head)\n\tr := s.getCellRune(head)\n\ts.setCell(head, snakeHead)\n\tgameOver := false\n\tswitch r {\n\tcase food.Ch:\n\t\ts.placeFood()\n\tcase border.Ch, snakeBody.Ch:\n\t\tgameOver = true\n\t\tfallthrough\n\tcase empty.Ch:\n\t\ts.setCell(s.body[0], empty)\n\t\ts.body = s.body[1:]\n\tdefault:\n\t\tpanic(r)\n\t}\n\ts.flush()\n\treturn gameOver\n}\n\nconst (\n\tfg = termbox.ColorWhite\n\tbg = termbox.ColorBlack\n)\n\n\n\nvar (\n\tempty     = termbox.Cell{Ch: ' ', Bg: bg, Fg: fg}\n\tborder    = termbox.Cell{Ch: '+', Bg: bg, Fg: termbox.ColorBlue}\n\tsnakeBody = termbox.Cell{Ch: '#', Bg: bg, Fg: termbox.ColorGreen}\n\tsnakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold}\n\tfood      = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed}\n)\n", "C": "\n\n\n\n\n\n\n\n\nchar nonblocking_getch();\nvoid positional_putch(int x, int y, char ch);\nvoid millisecond_sleep(int n);\nvoid init_screen();\nvoid update_screen();\nvoid close_screen();\n\n\n\n#ifdef __linux__\n#define _POSIX_C_SOURCE 200809L\n#include <time.h> \n#include <ncurses.h> \nchar nonblocking_getch() { return getch(); }\nvoid positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }\nvoid millisecond_sleep(int n) { \n\tstruct timespec t = { 0, n * 1000000 };\n\tnanosleep(&t, 0);\n\t\n}\nvoid update_screen() { refresh(); }\nvoid init_screen() {\n\tinitscr();\n\tnoecho();\n\tcbreak();\n\tnodelay(stdscr, TRUE);\n}\nvoid close_screen() { endwin(); }\n#endif\n\n\n#ifdef _WIN32\n#error \"not implemented\"\n#endif\n\n\n#include <time.h> \n#include <stdlib.h> \n\n#define w 80\n#define h 40\n\nint board[w * h];\nint head;\nenum Dir { N, E, S, W } dir;\nint quit;\n\nenum State { SPACE=0, FOOD=1, BORDER=2 };\n\n\n\nvoid age() {\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tif(board[i] < 0)\n\t\t\t++board[i];\n}\n\n\nvoid plant() {\n\tint r;\n\tdo\n\t\tr = rand() % (w * h);\n\twhile(board[r] != SPACE);\n\tboard[r] = FOOD;\n}\n\n\nvoid start(void) {\n        int i;\n\tfor(i = 0; i < w; ++i)\n\t\tboard[i] = board[i + (h - 1) * w] = BORDER;\n\tfor(i = 0; i < h; ++i)\n\t\tboard[i * w] = board[i * w + w - 1] = BORDER;\n\thead = w * (h - 1 - h % 2) / 2; \n\tboard[head] = -5;\n\tdir = N;\n\tquit = 0;\n\tsrand(time(0));\n\tplant();\n}\n\nvoid step() {\n\tint len = board[head];\n\tswitch(dir) {\n\t\tcase N: head -= w; break;\n\t\tcase S: head += w; break;\n\t\tcase W: --head; break;\n\t\tcase E: ++head; break;\n\t}\n\tswitch(board[head]) {\n\t\tcase SPACE:\n\t\t\tboard[head] = len - 1; \n\t\t\tage();\n\t\t\tbreak;\n\t\tcase FOOD:\n\t\t\tboard[head] = len - 1;\n\t\t\tplant();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tquit = 1;\n\t}\n}\n\nvoid show() {\n\tconst char * symbol = \" @.\";\n        int i;\n\tfor(i = 0; i < w * h; ++i)\n\t\tpositional_putch(i / w, i % w,\n\t\t\tboard[i] < 0 ? '#' : symbol[board[i]]);\n\tupdate_screen();\n}\n\nint main (int argc, char * argv[]) {\n\tinit_screen();\n\tstart();\n\tdo {\n\t\tshow();\n\t\tswitch(nonblocking_getch()) {\n\t\t\tcase 'i': dir = N; break;\n\t\t\tcase 'j': dir = W; break;\n\t\t\tcase 'k': dir = S; break;\n\t\t\tcase 'l': dir = E; break;\n\t\t\tcase 'q': quit = 1; break;\n\t\t}\n\t\tstep();\n\t\tmillisecond_sleep(100); \n\t\t\n\t}\n\twhile(!quit);\n\tmillisecond_sleep(999);\n\tclose_screen();\n\treturn 0;\n}\n"}
{"id": 45556, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 45557, "name": "Substring_Top and tail", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"unicode/utf8\"\n)\n\nfunc main() {\n    \n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \n    u := \"Δημοτική\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n", "C": "#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n"}
{"id": 45558, "name": "Legendre prime counting function", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\"\n    \"rcu\"\n)\n\nfunc cantorPair(x, y int) int {\n    if x < 0 || y < 0 {\n        log.Fatal(\"Arguments must be non-negative integers.\")\n    }\n    return (x*x + 3*x + 2*x*y + y + y*y) / 2\n}\n\nfunc pi(n int) int {\n    if n < 2 {\n        return 0\n    }\n    if n == 2 {\n        return 1\n    }\n    primes := rcu.Primes(int(math.Sqrt(float64(n))))\n    a := len(primes)\n    memoPhi := make(map[int]int)\n\n    var phi func(x, a int) int \n    phi = func(x, a int) int {\n        if a < 1 {\n            return x\n        }\n        if a == 1 {\n            return x - (x >> 1)\n        }\n        pa := primes[a-1]\n        if x <= pa {\n            return 1\n        }\n        key := cantorPair(x, a)\n        if v, ok := memoPhi[key]; ok {\n            return v\n        }\n        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)\n        return memoPhi[key]\n    }\n\n    return phi(n, a) + a - 1\n}\n\nfunc main() {\n    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {\n        fmt.Printf(\"10^%d  %d\\n\", i, pi(n))\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <time.h>\n\nconst uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};\n\n#define half(n) ((int64_t)((n) - 1) >> 1)\n\n#define divide(nm, d) ((uint64_t)((double)nm / (double)d))\n\nint64_t countPrimes(uint64_t n) {\n    if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;    \n    uint64_t rtlmt = (uint64_t)sqrt((double)n);\n    int64_t mxndx = (int64_t)((rtlmt - 1) / 2);\n    int arrlen = (int)(mxndx + 1);\n    uint32_t *smalls = malloc(arrlen * 4);\n    uint32_t *roughs = malloc(arrlen * 4);\n    int64_t *larges  = malloc(arrlen * 8);\n    for (int i = 0; i < arrlen; ++i) {\n        smalls[i] = (uint32_t)i;\n        roughs[i] = (uint32_t)(i + i + 1);\n        larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);\n    }\n    int cullbuflen = (int)((mxndx + 8) / 8);\n    uint8_t *cullbuf = calloc(cullbuflen, 1);\n    int64_t nbps = 0;\n    int rilmt = arrlen;\n    for (int64_t i = 1; ; ++i) {\n        int64_t sqri = (i + i) * (i + 1);\n        if (sqri > mxndx) break;\n        if (cullbuf[i >> 3] & masks[i & 7]) continue;\n        cullbuf[i >> 3] |= masks[i & 7];\n        uint64_t bp = (uint64_t)(i + i + 1);\n        for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {\n            cullbuf[c >> 3] |= masks[c & 7];\n        }\n        int nri = 0;\n        for (int ori = 0; ori < rilmt; ++ori) {\n            uint32_t r = roughs[ori];\n            int64_t rci = (int64_t)(r >> 1);\n            if (cullbuf[rci >> 3] & masks[rci & 7]) continue;\n            uint64_t d = (uint64_t)r * bp;\n            int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :\n                                       (int64_t)smalls[half(divide(n, d))];\n            larges[nri] = larges[ori] - t + nbps;\n            roughs[nri] = r;\n            nri++;\n        }\n        int64_t si = mxndx;\n        for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {\n            uint32_t c = smalls[pm >> 1];\n            uint64_t e = (pm * bp) >> 1;\n            for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;                           \n        }\n        rilmt = nri;\n        nbps++;\n    }\n    int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);\n    int ri, sri;\n    for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];\n    for (ri = 1; ; ++ri) {\n        uint64_t p = (uint64_t)roughs[ri];\n        uint64_t m = n / p;\n        int ei = (int)smalls[half((uint64_t)m/p)] - nbps;\n        if (ei <= ri) break;\n        ans -= (int64_t)((ei - ri) * (nbps + ri - 1));\n        for (sri = ri + 1; sri < ei + 1; ++sri) {\n            ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];\n        }\n    }\n    free(smalls);\n    free(roughs);\n    free(larges);\n    free(cullbuf);\n    return ans + 1;\n}\n\nint main() {\n    uint64_t n;\n    int i;\n    clock_t start = clock();\n    for (i = 0, n = 1; i < 10; ++i, n *= 10) {\n        printf(\"10^%d %ld\\n\", i, countPrimes(n));\n    }\n    clock_t end = clock();\n    printf(\"\\nTook %f seconds\\n\", (double) (end - start) / CLOCKS_PER_SEC);\n    return 0;\n}\n"}
{"id": 45559, "name": "Use another language to call a function", "Go": "package main\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc main() {\n    C.Run()\n}\n\nconst msg = \"Here am I\"\n\n\nfunc Query(cbuf *C.char, csiz *C.size_t) C.int {\n    if int(*csiz) <= len(msg) {\n        return 0\n    }\n    pbuf := uintptr(unsafe.Pointer(cbuf))\n    for i := 0; i < len(msg); i++ {\n        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]\n        pbuf++\n    }\n    *((*byte)(unsafe.Pointer(pbuf))) = 0\n    *csiz = C.size_t(len(msg) + 1)\n    return 1\n}\n", "C": "#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n   char     Buffer [1024];\n   size_t   Size = sizeof (Buffer);\n   \n   if (0 == Query (Buffer, &Size))\n   {\n      printf (\"failed to call Query\\n\");\n   }\n   else\n   {\n      char * Ptr = Buffer;\n      while (Size-- > 0) putchar (*Ptr++);\n      putchar ('\\n');\n   }\n}\n"}
{"id": 45560, "name": "Longest string challenge", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"os\"\n)\n\nfunc main() {\n    in := bufio.NewReader(os.Stdin)\n    var blankLine = \"\\n\"\n    var printLongest func(string) string\n    printLongest = func(candidate string) (longest string) {\n        longest = candidate\n        s, err := in.ReadString('\\n')\n        defer func() {\n            recover()\n            defer func() {\n                recover()\n            }()\n            _ = blankLine[0]\n            func() {\n                defer func() {\n                    recover()\n                }()\n                _ = s[len(longest)]\n                longest = s\n            }()\n            longest = printLongest(longest)\n            func() {\n                defer func() {\n                    recover()\n                    os.Stdout.WriteString(s)\n                }()\n                _ = longest[len(s)]\n                s = \"\"\n            }()\n        }()\n        _ = err.(error)\n        os.Stdout.WriteString(blankLine)\n        blankLine = \"\"\n        return\n    }\n    printLongest(\"\")\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n \nint cmp(const char *p, const char *q)\n{\n\twhile (*p && *q) p = &p[1], q = &q[1];\n\treturn *p;\n}\n \nint main()\n{\n\tchar line[65536];\n\tchar buf[1000000] = {0};\n\tchar *last = buf;\n\tchar *next = buf;\n \n\twhile (gets(line)) {\n\t\tstrcat(line, \"\\n\");\n\t\tif (cmp(last, line)) continue;\n\t\tif (cmp(line, last)) next = buf;\n\t\tlast = next;\n\t\tstrcpy(next, line);\n\t\twhile (*next) next = &next[1];\n\t}\n \n\tprintf(\"%s\", buf);\n\treturn 0;\n}\n"}
{"id": 45561, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 45562, "name": "Universal Turing machine", "Go": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n        Left  Motion = 'L'\n        Right Motion = 'R'\n        Stay  Motion = 'N'\n)\n\ntype Tape struct {\n        data      []Symbol\n        pos, left int\n        blank     Symbol\n}\n\n\n\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n        t := &Tape{\n                data:  data,\n                blank: blank,\n        }\n        if start < 0 {\n                t.Left(-start)\n        }\n        t.Right(start)\n        return t\n}\n\nfunc (t *Tape) Stay()          {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol   { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n        t2 := &Tape{\n                data:  make([]Symbol, len(t.Data())),\n                blank: t.blank,\n        }\n        copy(t2.data, t.Data())\n        t2.pos = t.pos - t.left\n        return t2\n}\n\nfunc (t *Tape) String() string {\n        s := \"\"\n        for i := t.left; i < len(t.data); i++ {\n                b := t.data[i]\n                if i == t.pos {\n                        s += \"[\" + string(b) + \"]\"\n                } else {\n                        s += \" \" + string(b) + \" \"\n                }\n        }\n        return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n        switch a {\n        case Left:\n                t.Left(1)\n        case Right:\n                t.Right(1)\n        case Stay:\n                t.Stay()\n        }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n        t.pos -= n\n        if t.pos < 0 {\n                \n                var sz int\n                for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                newl := len(newd) - cap(t.data[t.left:])\n                n := copy(newd[newl:], t.data[t.left:])\n                t.data = newd[:newl+n]\n                t.pos += newl - t.left\n                t.left = newl\n        }\n        if t.pos < t.left {\n                if t.blank != 0 {\n                        for i := t.pos; i < t.left; i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n                t.left = t.pos\n        }\n}\n\nfunc (t *Tape) Right(n int) {\n        t.pos += n\n        if t.pos >= cap(t.data) {\n                \n                var sz int\n                for sz = minSz; t.pos >= sz; sz <<= 1 {\n                }\n                newd := make([]Symbol, sz)\n                n := copy(newd[t.left:], t.data[t.left:])\n                t.data = newd[:t.left+n]\n        }\n        if i := len(t.data); t.pos >= i {\n                t.data = t.data[:t.pos+1]\n                if t.blank != 0 {\n                        for ; i < len(t.data); i++ {\n                                t.data[i] = t.blank\n                        }\n                }\n        }\n}\n\ntype State string\n\ntype Rule struct {\n        State\n        Symbol\n        Write Symbol\n        Motion\n        Next State\n}\n\nfunc (i *Rule) key() key       { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n        State\n        Symbol\n}\n\ntype action struct {\n        write Symbol\n        Motion\n        next State\n}\n\ntype Machine struct {\n        tape         *Tape\n        start, state State\n        transition   map[key]action\n        l            func(string, ...interface{}) \n}\n\nfunc NewMachine(rules []Rule) *Machine {\n        m := &Machine{transition: make(map[key]action, len(rules))}\n        if len(rules) > 0 {\n                m.start = rules[0].State\n        }\n        for _, r := range rules {\n                m.transition[r.key()] = r.action()\n        }\n        return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n        m.tape = input.Dup()\n        m.state = m.start\n        for cnt := 0; ; cnt++ {\n                if m.l != nil {\n                        m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n                }\n                sym := m.tape.Read()\n                act, ok := m.transition[key{m.state, sym}]\n                if !ok {\n                        return cnt, m.tape\n                }\n                m.tape.Write(act.write)\n                m.tape.Move(act.Motion)\n                m.state = act.next\n        }\n}\n", "C": "#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\nenum {\n    LEFT,\n    RIGHT,\n    STAY\n};\n\ntypedef struct {\n    int state1;\n    int symbol1;\n    int symbol2;\n    int dir;\n    int state2;\n} transition_t;\n\ntypedef struct tape_t tape_t;\nstruct tape_t {\n    int symbol;\n    tape_t *left;\n    tape_t *right;\n};\n\ntypedef struct {\n    int states_len;\n    char **states;\n    int final_states_len;\n    int *final_states;\n    int symbols_len;\n    char *symbols;\n    int blank;\n    int state;\n    int tape_len;\n    tape_t *tape;\n    int transitions_len;\n    transition_t ***transitions;\n} turing_t;\n\nint state_index (turing_t *t, char *state) {\n    int i;\n    for (i = 0; i < t->states_len; i++) {\n        if (!strcmp(t->states[i], state)) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nint symbol_index (turing_t *t, char symbol) {\n    int i;\n    for (i = 0; i < t->symbols_len; i++) {\n        if (t->symbols[i] == symbol) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid move (turing_t *t, int dir) {\n    tape_t *orig = t->tape;\n    if (dir == RIGHT) {\n        if (orig && orig->right) {\n            t->tape = orig->right;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->left = orig;\n                orig->right = t->tape;\n            }\n        }\n    }\n    else if (dir == LEFT) {\n        if (orig && orig->left) {\n            t->tape = orig->left;\n        }\n        else {\n            t->tape = calloc(1, sizeof (tape_t));\n            t->tape->symbol = t->blank;\n            if (orig) {\n                t->tape->right = orig;\n                orig->left = t->tape;\n            }\n        }\n    }\n}\n\nturing_t *create (int states_len, ...) {\n    va_list args;\n    va_start(args, states_len);\n    turing_t *t = malloc(sizeof (turing_t));\n    t->states_len = states_len;\n    t->states = malloc(states_len * sizeof (char *));\n    int i;\n    for (i = 0; i < states_len; i++) {\n        t->states[i] = va_arg(args, char *);\n    }\n    t->final_states_len = va_arg(args, int);\n    t->final_states = malloc(t->final_states_len * sizeof (int));\n    for (i = 0; i < t->final_states_len; i++) {\n        t->final_states[i] = state_index(t, va_arg(args, char *));\n    }\n    t->symbols_len = va_arg(args, int);\n    t->symbols = malloc(t->symbols_len);\n    for (i = 0; i < t->symbols_len; i++) {\n        t->symbols[i] = va_arg(args, int);\n    }\n    t->blank = symbol_index(t, va_arg(args, int));\n    t->state = state_index(t, va_arg(args, char *));\n    t->tape_len = va_arg(args, int);\n    t->tape = NULL;\n    for (i = 0; i < t->tape_len; i++) {\n        move(t, RIGHT);\n        t->tape->symbol = symbol_index(t, va_arg(args, int));\n    }\n    if (!t->tape_len) {\n        move(t, RIGHT);\n    }\n    while (t->tape->left) {\n        t->tape = t->tape->left;\n    }\n    t->transitions_len = va_arg(args, int);\n    t->transitions = malloc(t->states_len * sizeof (transition_t **));\n    for (i = 0; i < t->states_len; i++) {\n        t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));\n    }\n    for (i = 0; i < t->transitions_len; i++) {\n        transition_t *tran = malloc(sizeof (transition_t));\n        tran->state1 = state_index(t, va_arg(args, char *));\n        tran->symbol1 = symbol_index(t, va_arg(args, int));\n        tran->symbol2 = symbol_index(t, va_arg(args, int));\n        tran->dir = va_arg(args, int);\n        tran->state2 = state_index(t, va_arg(args, char *));\n        t->transitions[tran->state1][tran->symbol1] = tran;\n    }\n    va_end(args);\n    return t;\n}\n\nvoid print_state (turing_t *t) {\n    printf(\"%-10s \", t->states[t->state]);\n    tape_t *tape = t->tape;\n    while (tape->left) {\n        tape = tape->left;\n    }\n    while (tape) {\n        if (tape == t->tape) {\n            printf(\"[%c]\", t->symbols[tape->symbol]);\n        }\n        else {\n            printf(\" %c \", t->symbols[tape->symbol]);\n        }\n        tape = tape->right;\n    }\n    printf(\"\\n\");\n}\n\nvoid run (turing_t *t) {\n    int i;\n    while (1) {\n        print_state(t);\n        for (i = 0; i < t->final_states_len; i++) {\n            if (t->final_states[i] == t->state) {\n                return;\n            }\n        }\n        transition_t *tran = t->transitions[t->state][t->tape->symbol];\n        t->tape->symbol = tran->symbol2;\n        move(t, tran->dir);\n        t->state = tran->state2;\n    }\n}\n\nint main () {\n    printf(\"Simple incrementer\\n\");\n    turing_t *t = create(\n                2, \"q0\", \"qf\",\n          1, \"qf\",\n               2, 'B', '1',\n                 'B',\n         \"q0\",\n          3, '1', '1', '1',\n           2,\n                            \"q0\", '1', '1', RIGHT, \"q0\",\n                            \"q0\", 'B', '1', STAY, \"qf\"\n    );\n    run(t);\n    printf(\"\\nThree-state busy beaver\\n\");\n    t = create(\n                4, \"a\", \"b\", \"c\", \"halt\",\n          1, \"halt\",\n               2, '0', '1',\n                 '0',\n         \"a\",\n          0,\n           6,\n                            \"a\", '0', '1', RIGHT, \"b\",\n                            \"a\", '1', '1', LEFT, \"c\",\n                            \"b\", '0', '1', LEFT, \"a\",\n                            \"b\", '1', '1', RIGHT, \"b\",\n                            \"c\", '0', '1', LEFT, \"b\",\n                            \"c\", '1', '1', STAY, \"halt\"\n    );\n    run(t);\n    return 0;\n    printf(\"\\nFive-state two-symbol probable busy beaver\\n\");\n    t = create(\n                6, \"A\", \"B\", \"C\", \"D\", \"E\", \"H\",\n          1, \"H\",\n               2, '0', '1',\n                 '0',\n         \"A\",\n          0,\n           10,\n                            \"A\", '0', '1', RIGHT, \"B\",\n                            \"A\", '1', '1', LEFT, \"C\",\n                            \"B\", '0', '1', RIGHT, \"C\",\n                            \"B\", '1', '1', RIGHT, \"B\",\n                            \"C\", '0', '1', RIGHT, \"D\",\n                            \"C\", '1', '0', LEFT, \"E\",\n                            \"D\", '0', '1', LEFT, \"A\",\n                            \"D\", '1', '1', LEFT, \"D\",\n                            \"E\", '0', '1', STAY, \"H\",\n                            \"E\", '1', '0', LEFT, \"A\"\n    );\n    run(t);\n}\n"}
{"id": 45563, "name": "Create a file", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc createFile(fn string) {\n    f, err := os.Create(fn)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"file\", fn, \"created!\")\n    f.Close()\n}\n\nfunc createDir(dn string) {\n    err := os.Mkdir(dn, 0666)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"directory\", dn, \"created!\")\n}\n\nfunc main() {\n    createFile(\"input.txt\")\n    createFile(\"/input.txt\")\n    createDir(\"docs\")\n    createDir(\"/docs\")\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  FILE *fh = fopen(\"output.txt\", \"w\");\n  fclose(fh);\n\n  return 0;\n}\n"}
{"id": 45564, "name": "Unprimeable numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    return s\n}\n\nfunc main() {\n    fmt.Println(\"The first 35 unprimeable numbers are:\")\n    count := 0           \n    var firstNum [10]int \nouter:\n    for i, countFirst := 100, 0; countFirst < 10; i++ {\n        if isPrime(i) {\n            continue \n        }\n        s := strconv.Itoa(i)\n        le := len(s)\n        b := []byte(s)\n        for j := 0; j < le; j++ {\n            for k := byte('0'); k <= '9'; k++ {\n                if s[j] == k {\n                    continue\n                }\n                b[j] = k\n                n, _ := strconv.Atoi(string(b))\n                if isPrime(n) {\n                    continue outer\n                }\n            }\n            b[j] = s[j] \n        }\n        lastDigit := s[le-1] - '0'\n        if firstNum[lastDigit] == 0 {\n            firstNum[lastDigit] = i\n            countFirst++\n        }\n        count++\n        if count <= 35 {\n            fmt.Printf(\"%d \", i)\n        }\n        if count == 35 {\n            fmt.Print(\"\\n\\nThe 600th unprimeable number is: \")\n        }\n        if count == 600 {\n            fmt.Printf(\"%s\\n\\n\", commatize(i))\n        }\n    }\n\n    fmt.Println(\"The first unprimeable number that ends in:\")\n    for i := 0; i < 10; i++ {\n        fmt.Printf(\"  %d is: %9s\\n\", i, commatize(firstNum[i]))\n    }\n}\n", "C": "#include <assert.h>\n#include <locale.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct bit_array_tag {\n    uint32_t size;\n    uint32_t* array;\n} bit_array;\n\nbool bit_array_create(bit_array* b, uint32_t size) {\n    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));\n    if (array == NULL)\n        return false;\n    b->size = size;\n    b->array = array;\n    return true;\n}\n\nvoid bit_array_destroy(bit_array* b) {\n    free(b->array);\n    b->array = NULL;\n}\n\nvoid bit_array_set(bit_array* b, uint32_t index, bool value) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    if (value)\n        *p |= bit;\n    else\n        *p &= ~bit;\n}\n\nbool bit_array_get(const bit_array* b, uint32_t index) {\n    assert(index < b->size);\n    uint32_t* p = &b->array[index >> 5];\n    uint32_t bit = 1 << (index & 31);\n    return (*p & bit) != 0;\n}\n\ntypedef struct sieve_tag {\n    uint32_t limit;\n    bit_array not_prime;\n} sieve;\n\nbool sieve_create(sieve* s, uint32_t limit) {\n    if (!bit_array_create(&s->not_prime, limit/2))\n        return false;\n    for (uint32_t p = 3; p * p <= limit; p += 2) {\n        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {\n            uint32_t inc = 2 * p;\n            for (uint32_t q = p * p; q <= limit; q += inc)\n                bit_array_set(&s->not_prime, q/2 - 1, true);\n        }\n    }\n    s->limit = limit;\n    return true;\n}\n\nvoid sieve_destroy(sieve* s) {\n    bit_array_destroy(&s->not_prime);\n}\n\nbool is_prime(const sieve* s, uint32_t n) {\n    assert(n <= s->limit);\n    if (n == 2)\n        return true;\n    if (n < 2 || n % 2 == 0)\n        return false;\n    return bit_array_get(&s->not_prime, n/2 - 1) == false;\n}\n\n\nuint32_t count_digits(uint32_t n) {\n    uint32_t digits = 0;\n    for (; n > 0; ++digits)\n        n /= 10;\n    return digits;\n}\n\n\nuint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {\n    uint32_t p = 1;\n    uint32_t changed = 0;\n    for (; index > 0; p *= 10, n /= 10, --index)\n        changed += p * (n % 10);\n    changed += (10 * (n/10) + new_digit) * p;\n    return changed;\n}\n\n\nbool unprimeable(const sieve* s, uint32_t n) {\n    if (is_prime(s, n))\n        return false;\n    uint32_t d = count_digits(n);\n    for (uint32_t i = 0; i < d; ++i) {\n        for (uint32_t j = 0; j <= 9; ++j) {\n            uint32_t m = change_digit(n, i, j);\n            if (m != n && is_prime(s, m))\n                return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    const uint32_t limit = 10000000;\n    setlocale(LC_ALL, \"\");\n    sieve s = { 0 };\n    if (!sieve_create(&s, limit)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    printf(\"First 35 unprimeable numbers:\\n\");\n    uint32_t n = 100;\n    uint32_t lowest[10] = { 0 };\n    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {\n        if (unprimeable(&s, n)) {\n            if (count < 35) {\n                if (count != 0)\n                    printf(\", \");\n                printf(\"%'u\", n);\n            }\n            ++count;\n            if (count == 600)\n                printf(\"\\n600th unprimeable number: %'u\\n\", n);\n            uint32_t last_digit = n % 10;\n            if (lowest[last_digit] == 0) {\n                lowest[last_digit] = n;\n                ++found;\n            }\n        }\n    }\n    sieve_destroy(&s);\n    for (uint32_t i = 0; i < 10; ++i)\n        printf(\"Least unprimeable number ending in %u: %'u\\n\" , i, lowest[i]);\n    return 0;\n}\n"}
{"id": 45565, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 45566, "name": "Pascal's triangle_Puzzle", "Go": "package main\n\nimport \"fmt\"\n\n\ntype expr struct {\n    x, y, z float64 \n    c       float64 \n}\n\n\nfunc addExpr(a, b expr) expr {\n    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n}   \n    \n\nfunc subExpr(a, b expr) expr {\n    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n}   \n\n\nfunc mulExpr(a expr, c float64) expr {\n    return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n\n\nfunc addRow(l []expr) []expr {\n    if len(l) == 0 {\n        panic(\"wrong\")\n    }\n    r := make([]expr, len(l)-1)\n    for i := range r {\n        r[i] = addExpr(l[i], l[i+1])\n    }\n    return r\n}   \n\n\n\nfunc substX(a, b expr) expr {\n    if b.x == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n    if b.y == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n    if b.z == 0 {\n        panic(\"wrong\")\n    }\n    return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n\nfunc solveX(a expr) float64 {\n    if a.x == 0 || a.y != 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n    if a.x != 0 || a.y == 0 || a.z != 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n    if a.x != 0 || a.y != 0 || a.z == 0 {\n        panic(\"wrong\")\n    }\n    return -a.c / a.z\n}\n\nfunc main() {\n    \n    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n    fmt.Println(\"bottom row:\", r5)\n\n    \n    r4 := addRow(r5)\n    fmt.Println(\"next row up:\", r4)\n    r3 := addRow(r4)\n    fmt.Println(\"middle row:\", r3)\n\n    \n    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n    fmt.Println(\"xyz relation:\", xyz)\n    \n    r3[2] = substZ(r3[2], xyz)\n    fmt.Println(\"middle row after substituting for z:\", r3)\n\n    \n    b := expr{c: 40}\n    \n    xy := subExpr(r3[0], b)\n    fmt.Println(\"xy relation:\", xy)\n    \n    r3[0] = b\n\n    \n    r3[2] = substX(r3[2], xy)\n    fmt.Println(\"middle row after substituting for x:\", r3)\n    \n    \n    r2 := addRow(r3)\n    fmt.Println(\"next row up:\", r2)\n    r1 := addRow(r2)\n    fmt.Println(\"top row:\", r1)\n\n    \n    y := subExpr(r1[0], expr{c: 151})\n    fmt.Println(\"y relation:\", y)\n    \n    x := substY(xy, y)\n    fmt.Println(\"x relation:\", x)\n    \n    z := substX(substY(xyz, y), x)\n    fmt.Println(\"z relation:\", z)\n\n    \n    fmt.Println(\"x =\", solveX(x))\n    fmt.Println(\"y =\", solveY(y))\n    fmt.Println(\"z =\", solveZ(z)) \n}\n", "C": "\n\n#include <stdio.h>\n#include <math.h>\n\nvoid pascal(int a, int b, int mid, int top, int* x, int* y, int* z)\n{\n    double ytemp = (top - 4 * (a + b)) / 7.; \n    if(fmod(ytemp, 1.) >= 0.0001)\n    { \n        x = 0;\n        return;\n    } \n    *y = ytemp;\n    *x = mid - 2 * a - *y;\n    *z = *y - *x;\n}\nint main()\n{\n    int a = 11, b = 4, mid = 40, top = 151;\n    int x, y, z;\n    pascal(a, b, mid, top, &x, &y, &z);\n    if(x != 0)\n        printf(\"x: %d, y: %d, z: %d\\n\", x, y, z);\n    else printf(\"No solution\\n\");\n\n    return 0;\n}\n"}
{"id": 45567, "name": "Chernick's Carmichael numbers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar (\n    zero = new(big.Int)\n    prod = new(big.Int)\n    fact = new(big.Int)\n)\n\nfunc ccFactors(n, m uint64) (*big.Int, bool) {\n    prod.SetUint64(6*m + 1)\n    if !prod.ProbablyPrime(0) {\n        return zero, false\n    }\n    fact.SetUint64(12*m + 1)\n    if !fact.ProbablyPrime(0) { \n        return zero, false\n    }\n    prod.Mul(prod, fact)\n    for i := uint64(1); i <= n-2; i++ {\n        fact.SetUint64((1<<i)*9*m + 1)\n        if !fact.ProbablyPrime(0) {\n            return zero, false\n        }\n        prod.Mul(prod, fact)\n    }\n    return prod, true\n}\n\nfunc ccNumbers(start, end uint64) {\n    for n := start; n <= end; n++ {\n        m := uint64(1)\n        if n > 4 {\n            m = 1 << (n - 4)\n        }\n        for {\n            num, ok := ccFactors(n, m)\n            if ok {\n                fmt.Printf(\"a(%d) = %d\\n\", n, num)\n                break\n            }\n            if n <= 4 {\n                m++\n            } else {\n                m += 1 << (n - 4)\n            }\n        }\n    }\n}\n\nfunc main() {\n    ccNumbers(3, 9)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\ntypedef unsigned long long int u64;\n\n#define TRUE 1\n#define FALSE 0\n\nint primality_pretest(u64 k) {\n    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);\n    return TRUE;\n}\n\nint probprime(u64 k, mpz_t n) {\n    mpz_set_ui(n, k);\n    return mpz_probab_prime_p(n, 0);\n}\n\nint is_chernick(int n, u64 m, mpz_t z) {\n    u64 t = 9 * m;\n    if (primality_pretest(6 * m + 1) == FALSE) return FALSE;\n    if (primality_pretest(12 * m + 1) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;\n    if (probprime(6 * m + 1, z) == FALSE) return FALSE;\n    if (probprime(12 * m + 1, z) == FALSE) return FALSE;\n    for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;\n    return TRUE;\n}\n\nint main(int argc, char const *argv[]) {\n    mpz_t z;\n    mpz_inits(z, NULL);\n\n    for (int n = 3; n <= 10; n ++) {\n        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;\n\n        if (n > 5) multiplier *= 5;\n\n        for (u64 k = 1; ; k++) {\n            u64 m = k * multiplier;\n\n            if (is_chernick(n, m, z) == TRUE) {\n                printf(\"a(%d) has m = %llu\\n\", n, m);\n                break;\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 45568, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 45569, "name": "Find if a point is within a triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n    return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n    checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n    checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n    return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n    xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n    yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n    yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n    return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n    p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n    dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n    if dotProduct < 0 {\n        return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n    } else if dotProduct <= 1 {\n        p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n        return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n    } else {\n        return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n    }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n    if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n        return false\n    }\n    if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n        return true\n    }\n    if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n        return true\n    }\n    if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n        return true\n    }\n    return false\n}\n\nfunc main() {\n    pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n    tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 := tri[0][0], tri[0][1]\n    x2, y2 := tri[1][0], tri[1][1]\n    x3, y3 := tri[2][0], tri[2][1]\n    for _, pt := range pts {\n        x, y := pt[0], pt[1]\n        within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n        fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n    }\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n    fmt.Println(\"Triangle is\", tri)\n    x1, y1 = tri[0][0], tri[0][1]\n    x2, y2 = tri[1][0], tri[1][1]\n    x3, y3 = tri[2][0], tri[2][1]\n    x := x1 + (3.0/7)*(x2-x1)\n    y := y1 + (3.0/7)*(y2-y1)\n    pt := [2]float64{x, y}\n    within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n    fmt.Println()\n    tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n    fmt.Println(\"Triangle is\", tri)\n    x3 = tri[2][0]\n    y3 = tri[2][1]\n    within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n    fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = 0.000001;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n    return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n    double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n    double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n    return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    double xMin = min(x1, min(x2, x3)) - EPS;\n    double xMax = max(x1, max(x2, x3)) + EPS;\n    double yMin = min(y1, min(y2, y3)) - EPS;\n    double yMax = max(y1, max(y2, y3)) + EPS;\n    return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n    double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n    if (dotProduct < 0) {\n        return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n    } else if (dotProduct <= 1) {\n        double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n        return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n    } else {\n        return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n        return false;\n    }\n    if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n        return true;\n    }\n    return false;\n}\n\nvoid printPoint(double x, double y) {\n    printf(\"(%f, %f)\", x, y);\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n    printf(\"Triangle is [\");\n    printPoint(x1, y1);\n    printf(\", \");\n    printPoint(x2, y2);\n    printf(\", \");\n    printPoint(x3, y3);\n    printf(\"] \\n\");\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n    printTriangle(x1, y1, x2, y2, x3, y3);\n    printf(\"Point \");\n    printPoint(x, y);\n    printf(\" is within triangle? \");\n    if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n        printf(\"true\\n\");\n    } else {\n        printf(\"false\\n\");\n    }\n}\n\nint main() {\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n    test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 45570, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 45571, "name": "Tau function", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%2d  \", countDivisors(i))\n        if i%20 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (unsigned int p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n\n    printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%3d\", divisor_count(n));\n        if (n % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 45572, "name": "Create an object at a given address", "Go": "package main\n\nimport(\n\t\"fmt\"\n\t\"unsafe\"\n\t\"reflect\"\n)\n\nfunc pointer() {\n\tfmt.Printf(\"Pointer:\\n\")\n\n\t\n\t\n\t\n\t\n\tvar i int\n\tp := &i\n\n\tfmt.Printf(\"Before:\\n\\t%v: %v, %v\\n\", p, *p, i)\n\n\t*p = 3\n\n\tfmt.Printf(\"After:\\n\\t%v: %v, %v\\n\", p, *p, i)\n}\n\nfunc slice() {\n\tfmt.Printf(\"Slice:\\n\")\n\n\tvar a [10]byte\n\n\t\n\t\n\t\n\t\n\t\n\tvar h reflect.SliceHeader\n\th.Data = uintptr(unsafe.Pointer(&a)) \n\th.Len = len(a)\n\th.Cap = len(a)\n\n\t\n\ts := *(*[]byte)(unsafe.Pointer(&h))\n\n\tfmt.Printf(\"Before:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n\n\t\n\t\n\tcopy(s, \"A string.\")\n\n\tfmt.Printf(\"After:\\n\\ts: %v\\n\\ta: %v\\n\", s, a)\n}\n\nfunc main() {\n\tpointer()\n\tfmt.Println()\n\n\tslice()\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n  int intspace;\n  int *address;\n\n  address = &intspace; \n  *address = 65535;\n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  \n  *((char*)address) = 0x00;\n  *((char*)address+1) = 0x00;\n  *((char*)address+2) = 0xff;\n  *((char*)address+3) = 0xff; \n  \n  printf(\"%p: %08x (=%08x)\\n\", address, *address, intspace);\n  return 0;\n}\n"}
{"id": 45573, "name": "Sequence of primorial primes", "Go": "package main\n  \nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    one := big.NewInt(1)\n    pm := big.NewInt(1) \n    var px, nx int\n    var pb big.Int \n    primes(4000, func(p int64) bool {\n        pm.Mul(pm, pb.SetInt64(p))\n        px++\n        if pb.Add(pm, one).ProbablyPrime(0) ||\n            pb.Sub(pm, one).ProbablyPrime(0) {\n            fmt.Print(px, \" \")\n            nx++\n            if nx == 20 {\n                fmt.Println()\n                return false\n            }\n        }\n        return true\n    })\n}\n\n\n\n\nfunc primes(limit int, f func(int64) bool) {\n    c := make([]bool, limit)\n    c[0] = true\n    c[1] = true\n    lm := int64(limit)\n    p := int64(2)\n    for {\n        f(p)\n        p2 := p * p\n        if p2 >= lm {\n            break\n        }\n        for i := p2; i < lm; i += p {\n            c[i] = true\n        }\n        for {\n            p++\n            if !c[p] {\n                break\n            }\n        }\n    }\n    for p++; p < lm; p++ {\n        if !c[p] && !f(p) {\n            break\n        }\n    }\n}\n", "C": "#include <gmp.h>\n\nint main(void)\n{\n    mpz_t p, s;\n    mpz_init_set_ui(p, 1);\n    mpz_init_set_ui(s, 1);\n\n    for (int n = 1, i = 0; i < 20; n++) {\n        mpz_nextprime(s, s);\n        mpz_mul(p, p, s);\n\n        mpz_add_ui(p, p, 1);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_sub_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_sub_ui(p, p, 2);\n        if (mpz_probab_prime_p(p, 25)) {\n            mpz_add_ui(p, p, 1);\n            gmp_printf(\"%d\\n\", n);\n            i++;\n            continue;\n        }\n\n        mpz_add_ui(p, p, 1);\n    }\n\n    mpz_clear(s);\n    mpz_clear(p);\n}\n"}
{"id": 45574, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 45575, "name": "Bioinformatics_base count", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    dna := \"\" +\n        \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n        \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n        \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n        \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n        \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n        \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n        \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n        \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n        \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n        \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += 50 {\n        k := i + 50\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\")\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct genome{\n    char* strand;\n    int length;\n    struct genome* next;\n}genome;\n\ngenome* genomeData;\nint totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num = num/10;\n        len++;\n    }\n\n    return len;\n}\n\nvoid buildGenome(char str[100]){\n    int len = strlen(str),i;\n    genome *genomeIterator, *newGenome; \n\n    totalLength += len;\n\n    for(i=0;i<len;i++){\n        switch(str[i]){\n            case 'A': Adenine++;\n                break;\n            case 'T': Thymine++;\n                break;\n            case 'C': Cytosine++;\n                break;\n            case 'G': Guanine++;\n                break;\n        };\n    }\n\n    if(genomeData==NULL){\n        genomeData = (genome*)malloc(sizeof(genome));\n\n        genomeData->strand = (char*)malloc(len*sizeof(char));\n        strcpy(genomeData->strand,str);\n        genomeData->length = len;\n\n        genomeData->next = NULL;\n    }\n\n    else{\n        genomeIterator = genomeData;\n\n        while(genomeIterator->next!=NULL)\n            genomeIterator = genomeIterator->next;\n\n        newGenome = (genome*)malloc(sizeof(genome));\n\n        newGenome->strand = (char*)malloc(len*sizeof(char));\n        strcpy(newGenome->strand,str);\n        newGenome->length = len;\n\n        newGenome->next = NULL;\n        genomeIterator->next = newGenome;\n    }\n}\n\nvoid printGenome(){\n    genome* genomeIterator = genomeData;\n\n    int width = numDigits(totalLength), len = 0;\n\n    printf(\"Sequence:\\n\");\n\n    while(genomeIterator!=NULL){\n        printf(\"\\n%*d%3s%3s\",width+1,len,\":\",genomeIterator->strand);\n        len += genomeIterator->length;\n\n        genomeIterator = genomeIterator->next;\n    }\n\n    printf(\"\\n\\nBase Count\\n----------\\n\\n\");\n\n    printf(\"%3c%3s%*d\\n\",'A',\":\",width+1,Adenine);\n    printf(\"%3c%3s%*d\\n\",'T',\":\",width+1,Thymine);\n    printf(\"%3c%3s%*d\\n\",'C',\":\",width+1,Cytosine);\n    printf(\"%3c%3s%*d\\n\",'G',\":\",width+1,Guanine);\n    printf(\"\\n%3s%*d\\n\",\"Total:\",width+1,Adenine + Thymine + Cytosine + Guanine);\n\n    free(genomeData);\n}\n\nint main(int argc,char** argv)\n{\n    char str[100];\n    int counter = 0, len;\n    \n    if(argc!=2){\n        printf(\"Usage : %s <Gene file name>\\n\",argv[0]);\n        return 0;\n    }\n\n    FILE *fp = fopen(argv[1],\"r\");\n\n    while(fscanf(fp,\"%s\",str)!=EOF)\n        buildGenome(str);\n    fclose(fp);\n\n    printGenome();\n\n    return 0;\n}\n"}
{"id": 45576, "name": "Dining philosophers", "Go": "package main\n\nimport (\n    \"hash/fnv\"\n    \"log\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\n\n\nvar ph = []string{\"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\"}\n\nconst hunger = 3                \nconst think = time.Second / 100 \nconst eat = time.Second / 100   \n\nvar fmt = log.New(os.Stdout, \"\", 0) \n\nvar done = make(chan bool)\n\n\n\ntype fork byte\n\n\n\n\n\n\n\n\nfunc philosopher(phName string,\n    dominantHand, otherHand chan fork, done chan bool) {\n    fmt.Println(phName, \"seated\")\n    \n    \n    h := fnv.New64a()\n    h.Write([]byte(phName))\n    rg := rand.New(rand.NewSource(int64(h.Sum64())))\n    \n    rSleep := func(t time.Duration) {\n        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))\n    }\n    for h := hunger; h > 0; h-- {\n        fmt.Println(phName, \"hungry\")\n        <-dominantHand \n        <-otherHand\n        fmt.Println(phName, \"eating\")\n        rSleep(eat)\n        dominantHand <- 'f' \n        otherHand <- 'f'\n        fmt.Println(phName, \"thinking\")\n        rSleep(think)\n    }\n    fmt.Println(phName, \"satisfied\")\n    done <- true\n    fmt.Println(phName, \"left the table\")\n}\n\nfunc main() {\n    fmt.Println(\"table empty\")\n    \n    \n    place0 := make(chan fork, 1)\n    place0 <- 'f' \n    placeLeft := place0\n    for i := 1; i < len(ph); i++ {\n        placeRight := make(chan fork, 1)\n        placeRight <- 'f'\n        go philosopher(ph[i], placeLeft, placeRight, done)\n        placeLeft = placeRight\n    }\n    \n    \n    \n    go philosopher(ph[0], place0, placeLeft, done)\n    \n    for range ph {\n        <-done \n    }\n    fmt.Println(\"table empty\")\n}\n", "C": "#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdarg.h>\n\n#define N 5\nconst char *names[N] = { \"Aristotle\", \"Kant\", \"Spinoza\", \"Marx\", \"Russell\" };\npthread_mutex_t forks[N];\n\n#define M 5 \nconst char *topic[M] = { \"Spaghetti!\", \"Life\", \"Universe\", \"Everything\", \"Bathroom\" };\n\n#define lock pthread_mutex_lock\n#define unlock pthread_mutex_unlock\n#define xy(x, y) printf(\"\\033[%d;%dH\", x, y)\n#define clear_eol(x) print(x, 12, \"\\033[K\")\nvoid print(int y, int x, const char *fmt, ...)\n{\n\tstatic pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;\n\tva_list ap;\n\tva_start(ap, fmt);\n\n\tlock(&screen);\n\txy(y + 1, x), vprintf(fmt, ap);\n\txy(N + 1, 1), fflush(stdout);\n\tunlock(&screen);\n}\n\nvoid eat(int id)\n{\n\tint f[2], ration, i; \n\tf[0] = f[1] = id;\n\n\t\n\tf[id & 1] = (id + 1) % N;\n\n\tclear_eol(id);\n\tprint(id, 12, \"..oO (forks, need forks)\");\n\n\tfor (i = 0; i < 2; i++) {\n\t\tlock(forks + f[i]);\n\t\tif (!i) clear_eol(id);\n\n\t\tprint(id, 12 + (f[i] != id) * 6, \"fork%d\", f[i]);\n\t\t\n\t\tsleep(1);\n\t}\n\n\tfor (i = 0, ration = 3 + rand() % 8; i < ration; i++)\n\t\tprint(id, 24 + i * 4, \"nom\"), sleep(1);\n\n\t\n\tfor (i = 0; i < 2; i++) unlock(forks + f[i]);\n}\n\nvoid think(int id)\n{\n\tint i, t;\n\tchar buf[64] = {0};\n\n\tdo {\n\t\tclear_eol(id);\n\t\tsprintf(buf, \"..oO (%s)\", topic[t = rand() % M]);\n\n\t\tfor (i = 0; buf[i]; i++) {\n\t\t\tprint(id, i+12, \"%c\", buf[i]);\n\t\t\tif (i < 5) usleep(200000);\n\t\t}\n\t\tusleep(500000 + rand() % 1000000);\n\t} while (t);\n}\n\nvoid* philosophize(void *a)\n{\n\tint id = *(int*)a;\n\tprint(id, 1, \"%10s\", names[id]);\n\twhile(1) think(id), eat(id);\n}\n\nint main()\n{\n\tint i, id[N];\n\tpthread_t tid[N];\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_mutex_init(forks + (id[i] = i), 0);\n\n\tfor (i = 0; i < N; i++)\n\t\tpthread_create(tid + i, 0, philosophize, id + i);\n\n\t\n\treturn pthread_join(tid[0], 0);\n}\n"}
{"id": 45577, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 45578, "name": "Factorions", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \n    var fact [12]uint64\n    fact[0] = 1\n    for n := uint64(1); n < 12; n++ {\n        fact[n] = fact[n-1] * n\n    }\n\n    for b := 9; b <= 12; b++ {\n        fmt.Printf(\"The factorions for base %d are:\\n\", b)\n        for i := uint64(1); i < 1500000; i++ {\n            digits := strconv.FormatUint(i, b)\n            sum := uint64(0)\n            for _, digit := range digits {\n                if digit < 'a' {\n                    sum += fact[digit-'0']\n                } else {\n                    sum += fact[digit+10-'a']\n                }\n            }\n            if sum == i {\n                fmt.Printf(\"%d \", i)\n            }\n        }\n        fmt.Println(\"\\n\")\n    }\n}\n", "C": "#include <stdio.h>\n\nint main() {    \n    int n, b, d;\n    unsigned long long i, j, sum, fact[12];\n    \n    fact[0] = 1;\n    for (n = 1; n < 12; ++n) {\n        fact[n] = fact[n-1] * n;\n    }\n\n    for (b = 9; b <= 12; ++b) {\n        printf(\"The factorions for base %d are:\\n\", b);\n        for (i = 1; i < 1500000; ++i) {\n            sum = 0;\n            j = i;\n            while (j > 0) {\n                d = j % b;\n                sum += fact[d];\n                j /= b;\n            }\n            if (sum == i) printf(\"%llu \", i);\n        }\n        printf(\"\\n\\n\");\n    }\n    return 0;\n}\n"}
{"id": 45579, "name": "Logistic curve fitting in epidemiology", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"github.com/maorshutman/lm\"\n    \"log\"\n    \"math\"\n)\n\nconst (\n    K  = 7_800_000_000 \n    n0 = 27            \n)\n\nvar y = []float64{\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,\n    2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,\n    24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,\n    60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,\n    76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,\n    85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,\n    105824, 109695, 114232, 118610, 125497, 133852, 143227,\n    151367, 167418, 180096, 194836, 213150, 242364, 271106,\n    305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054,\n    1174652,\n}\n\nfunc f(dst, p []float64) {\n    for i := 0; i < len(y); i++ {\n        t := float64(i)\n        dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]\n    }\n}\n\nfunc main() {\n    j := lm.NumJac{Func: f}\n    prob := lm.LMProblem{\n        Dim:        1,\n        Size:       len(y),\n        Func:       f,\n        Jac:        j.Jac,\n        InitParams: []float64{0.5},\n        Tau:        1e-6,\n        Eps1:       1e-8,\n        Eps2:       1e-8,\n    }\n    res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})\n    if err != nil {\n        log.Fatal(err)\n    }\n    r := res.X[0]\n    fmt.Printf(\"The logistic curve r for the world data is %.8f\\n\", r)\n    fmt.Printf(\"R0 is then approximately equal to %.7f\\n\", math.Exp(12*r))\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n\nconst double K = 7.8e9;\nconst int n0 = 27;\nconst double actual[] = {\n    27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,\n    61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,\n    4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,\n    31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,\n    69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,\n    80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,\n    95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,\n    133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,\n    271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,\n    656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652\n};\nconst size_t actual_size = sizeof(actual) / sizeof(double);\n\ndouble f(double r) {\n    double sq = 0;\n    size_t i;\n    for (i = 0; i < actual_size; ++i) {\n        double eri = exp(r * i);\n        double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);\n        double diff = guess - actual[i];\n        sq += diff * diff;\n    }\n    return sq;\n}\n\ndouble solve(double (*fn)(double), double guess, double epsilon) {\n    double delta, f0, factor;\n    for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;\n        delta > epsilon && guess != guess - delta;\n        delta *= factor) {\n        double nf = (*fn)(guess - delta);\n        if (nf < f0) {\n            f0 = nf;\n            guess -= delta;\n        } else {\n            nf = fn(guess + delta);\n            if (nf < f0) {\n                f0 = nf;\n                guess += delta;\n            } else {\n                factor = 0.5;\n            }\n        }\n    }\n    return guess;\n}\n\ndouble solve_default(double (*fn)(double)) {\n    return solve(fn, 0.5, 0);\n}\n\nint main() {\n    double r = solve_default(f);\n    double R0 = exp(12 * r);\n    printf(\"r = %f, R0 = %f\\n\", r, R0);\n    return 0;\n}\n"}
{"id": 45580, "name": "Sorting algorithms_Strand sort", "Go": "package main\n\nimport \"fmt\"\n\ntype link struct {\n    int\n    next *link\n}\n\nfunc linkInts(s []int) *link {\n    if len(s) == 0 {\n        return nil\n    }\n    return &link{s[0], linkInts(s[1:])}\n}\n\nfunc (l *link) String() string {\n    if l == nil {\n        return \"nil\"\n    }\n    r := fmt.Sprintf(\"[%d\", l.int)\n    for l = l.next; l != nil; l = l.next {\n        r = fmt.Sprintf(\"%s %d\", r, l.int)\n    }\n    return r + \"]\"\n}\n\nfunc main() {\n    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})\n    fmt.Println(\"before:\", a)\n    b := strandSort(a)\n    fmt.Println(\"after: \", b)\n}\n\nfunc strandSort(a *link) (result *link) {\n    for a != nil {\n        \n        sublist := a\n        a = a.next\n        sTail := sublist\n        for p, pPrev := a, a; p != nil; p = p.next {\n            if p.int > sTail.int {\n                \n                sTail.next = p\n                sTail = p\n                \n                if p == a {\n                    a = p.next\n                } else {\n                    pPrev.next = p.next\n                }\n            } else {\n                pPrev = p\n            }\n        }\n        sTail.next = nil \n        if result == nil {\n            result = sublist\n            continue\n        }\n        \n        var m, rr *link\n        if sublist.int < result.int {\n            m = sublist\n            sublist = m.next\n            rr = result\n        } else {\n            m = result\n            rr = m.next\n        }\n        result = m\n        for {\n            if sublist == nil {\n                m.next = rr\n                break\n            }\n            if rr == nil {\n                m.next = sublist\n                break\n            }\n            if sublist.int < rr.int {\n                m.next = sublist\n                m = sublist\n                sublist = m.next\n            } else {\n                m.next = rr\n                m = rr\n                rr = m.next\n            }\n        }\n    }\n    return\n}\n", "C": "#include <stdio.h>\n\ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n\nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n\nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n\nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n\nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n\n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n\nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n\n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n\n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n\n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n\n\t\tmerge(&res, &strand);\n\t}\n\n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n\nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};\n#\tdefine SIZE sizeof(x)/sizeof(int)\n\n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n\n\treturn 0;\n}\n"}
{"id": 45581, "name": "Additive primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := 5\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc sumDigits(n int) int {\n    sum := 0\n    for n > 0 {\n        sum += n % 10\n        n /= 10\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"Additive primes less than 500:\")\n    i := 2\n    count := 0\n    for {\n        if isPrime(i) && isPrime(sumDigits(i)) {\n            count++\n            fmt.Printf(\"%3d  \", i)\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        if i > 2 {\n            i += 2\n        } else {\n            i++\n        }\n        if i > 499 {\n            break\n        }\n    }\n    fmt.Printf(\"\\n\\n%d additive primes found.\\n\", count)\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nvoid memoizeIsPrime( bool * result, const int N )\n{\n    result[2] = true;\n    result[3] = true;\n    int prime[N];\n    prime[0] = 3;\n    int end = 1;\n    for (int n = 5; n < N; n += 2)\n    {\n        bool n_is_prime = true;\n        for (int i = 0; i < end; ++i)\n        {\n            const int PRIME = prime[i];\n            if (n % PRIME == 0)\n            {\n                n_is_prime = false;\n                break;\n            }\n            if (PRIME * PRIME > n)\n            {\n                break;\n            }\n        }\n        if (n_is_prime)\n        {\n            prime[end++] = n;\n            result[n] = true;\n        }\n    }\n}\n\nint sumOfDecimalDigits( int n )\n{\n    int sum = 0;\n    while (n > 0)\n    {\n        sum += n % 10;\n        n /= 10;\n    }\n    return sum;\n}\n\nint main( void )\n{\n    const int N = 500;\n\n    printf( \"Rosetta Code: additive primes less than %d:\\n\", N );\n\n    bool is_prime[N];\n    memset( is_prime, 0, sizeof(is_prime) );\n    memoizeIsPrime( is_prime, N );\n\n    printf( \"   2\" );\n    int count = 1;\n    for (int i = 3; i < N; i += 2)\n    {\n        if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])\n        {\n            printf( \"%4d\", i );\n            ++count;\n            if ((count % 10) == 0)\n            {\n                printf( \"\\n\" );\n            }\n        }\n    }\n    printf( \"\\nThose were %d additive primes.\\n\", count );\n    return 0;\n}\n"}
{"id": 45582, "name": "Inverted syntax", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n"}
{"id": 45583, "name": "Inverted syntax", "Go": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n    if cond {\n        return bool(ib)\n    }\n    return bool(!ib)\n}\n\nfunc main() {\n    var needUmbrella bool\n    raining := true\n\n    \n    if raining {\n        needUmbrella = true\n    }\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n    \n    raining = false\n    needUmbrella = itrue.iif(raining)\n    fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define otherwise       do { register int _o = 2; do { switch (_o) {  case 1:\n#define given(Mc)       ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)\n\n\nint foo() { return 1; }\n\nmain()\n{\n        int a = 0;\n\n        otherwise  a = 4 given (foo());\n        printf(\"%d\\n\", a);\n        exit(0);\n}\n"}
{"id": 45584, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 45585, "name": "Perfect totient numbers", "Go": "package main\n\nimport \"fmt\"\n\nfunc gcd(n, k int) int {\n    if n < k || k < 1 {\n        panic(\"Need n >= k and k >= 1\")\n    }\n\n    s := 1\n    for n&1 == 0 && k&1 == 0 {\n        n >>= 1\n        k >>= 1\n        s <<= 1\n    }\n\n    t := n\n    if n&1 != 0 {\n        t = -k\n    }\n    for t != 0 {\n        for t&1 == 0 {\n            t >>= 1\n        }\n        if t > 0 {\n            n = t\n        } else {\n            k = -t\n        }\n        t = n - k\n    }\n    return n * s\n}\n\nfunc totient(n int) int {\n    tot := 0\n    for k := 1; k <= n; k++ {\n        if gcd(n, k) == 1 {\n            tot++\n        }\n    }\n    return tot\n}\n\nfunc main() {\n    var perfect []int\n    for n := 1; len(perfect) < 20; n += 2 {\n        tot := n\n        sum := 0\n        for tot != 1 {\n            tot = totient(tot)\n            sum += tot\n        }\n        if sum == n {\n            perfect = append(perfect, n)\n        }\n    }\n    fmt.Println(\"The first 20 perfect totient numbers are:\")\n    fmt.Println(perfect)\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nlong totient(long n){\n\tlong tot = n,i;\n\t\n\tfor(i=2;i*i<=n;i+=2){\n\t\tif(n%i==0){\n\t\t\twhile(n%i==0)\n\t\t\t\tn/=i;\n\t\t\ttot-=tot/i;\n\t\t}\n\t\t\n\t\tif(i==2)\n\t\t\ti=1;\n\t}\n\t\n\tif(n>1)\n\t\ttot-=tot/n;\n\t\n\treturn tot;\n}\n\nlong* perfectTotients(long n){\n\tlong *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;\n\t\n\tfor(m=1;count<n;m++){\n\t\t tot = m;\n\t\t sum = 0;\n        while(tot != 1){\n            tot = totient(tot);\n            sum += tot;\n        }\n        if(sum == m)\n\t\t\tptList[count++] = m;\n        }\n\t\t\n\t\treturn ptList;\n}\n\nlong main(long argC, char* argV[])\n{\n\tlong *ptList,i,n;\n\t\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <number of perfect Totient numbers required>\",argV[0]);\n\telse{\n\t\tn = atoi(argV[1]);\n\t\t\n\t\tptList = perfectTotients(n);\n\t\t\n\t\tprintf(\"The first %d perfect Totient numbers are : \\n[\",n);\n\t\t\n\t\tfor(i=0;i<n;i++)\n\t\t\tprintf(\" %d,\",ptList[i]);\n\t\tprintf(\"\\b]\");\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 45586, "name": "Delegates", "Go": "package main\nimport \"fmt\"\n\ntype Delegator struct {\n    delegate interface{} \n}\n\n\ntype Thingable interface {\n    thing() string\n}\n\nfunc (self Delegator) operation() string {\n    if v, ok := self.delegate.(Thingable); ok {\n        return v.thing()\n    }\n    return \"default implementation\"\n}\n\ntype Delegate int \n\nfunc (Delegate) thing() string {\n    return \"delegate implementation\"\n}\n\nfunc main() {\n    \n    a := Delegator{}\n    fmt.Println(a.operation()) \n\n    \n    a.delegate = \"A delegate may be any object\"\n    fmt.Println(a.operation()) \n\n    \n    var d Delegate\n    a.delegate = d\n    fmt.Println(a.operation()) \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef const char * (*Responder)( int p1);\n\ntypedef struct sDelegate {\n    Responder operation;\n} *Delegate;\n\n\nDelegate NewDelegate( Responder rspndr )\n{\n    Delegate dl = malloc(sizeof(struct sDelegate));\n    dl->operation = rspndr;\n    return dl;\n}\n\n\nconst char *DelegateThing(Delegate dl, int p1)\n{\n    return  (dl->operation)? (*dl->operation)(p1) : NULL;\n}\n\n\ntypedef struct sDelegator {\n    int     param;\n    char    *phrase;\n    Delegate delegate;\n} *Delegator;\n\nconst char * defaultResponse( int p1)\n{\n    return \"default implementation\";\n}\n\nstatic struct sDelegate defaultDel = { &defaultResponse };\n\n\nDelegator NewDelegator( int p, char *phrase)\n{\n    Delegator d  = malloc(sizeof(struct sDelegator));\n    d->param = p;\n    d->phrase = phrase;\n    d->delegate = &defaultDel;\t\n    return d;\n}\n\n\nconst char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)\n{\n    const char *rtn;\n    if (delroy) {\n        rtn = DelegateThing(delroy, p1);\n        if (!rtn) {\t\t\t\n            rtn = DelegateThing(theDelegator->delegate, p1);\n        }\n    }\n    else \t\t\n        rtn = DelegateThing(theDelegator->delegate, p1);\n\n    printf(\"%s\\n\", theDelegator->phrase );\n    return rtn;\n}\n\n\nconst char *thing1( int p1)\n{\n    printf(\"We're in thing1 with value %d\\n\" , p1);\n    return \"delegate implementation\";\n}\n\nint main()\n{\n    Delegate del1 = NewDelegate(&thing1);\n    Delegate del2 = NewDelegate(NULL);\n    Delegator theDelegator = NewDelegator( 14, \"A stellar vista, Baby.\");\n\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, NULL));\n    printf(\"Delegator returns %s\\n\\n\", \n            Delegator_Operation( theDelegator, 3, del1));\n    printf(\"Delegator returns %s\\n\\n\",\n            Delegator_Operation( theDelegator, 3, del2));\n    return 0;\n}\n"}
{"id": 45587, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 45588, "name": "Sum of divisors", "Go": "package main\n\nimport \"fmt\"\n\nfunc sumDivisors(n int) int {\n    sum := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            sum += i\n            j := n / i\n            if j != i {\n                sum += j\n            }\n        }\n        i += k\n    }\n    return sum\n}\n\nfunc main() {\n    fmt.Println(\"The sums of positive divisors for the first 100 positive integers are:\")\n    for i := 1; i <= 100; i++ {\n        fmt.Printf(\"%3d   \", sumDivisors(i))\n        if i%10 == 0 {\n            fmt.Println()\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\n\nunsigned int divisor_sum(unsigned int n) {\n    unsigned int total = 1, power = 2;\n    unsigned int p;\n    \n    for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n        total += power;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int sum = 1;\n        for (power = p; n % p == 0; power *= p, n /= p) {\n            sum += power;\n        }\n        total *= sum;\n    }\n    \n    if (n > 1) {\n        total *= n + 1;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int n;\n    printf(\"Sum of divisors for the first %d positive integers:\\n\", limit);\n    for (n = 1; n <= limit; ++n) {\n        printf(\"%4d\", divisor_sum(n));\n        if (n % 10 == 0) {\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n"}
{"id": 45589, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 45590, "name": "Abbreviations, easy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar table =\n    \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \" +\n    \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n    \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n     \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \" +\n    \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \" +\n    \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \" +\n    \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n    results := make([]string, 0)\n    if len(words) == 0 {\n        return results\n    }\n    for _, word := range words {\n        matchFound := false\n        wlen := len(word)\n        for i, command := range commands {\n            if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n                continue\n            }\n            c := strings.ToUpper(command)\n            w := strings.ToUpper(word)\n            if strings.HasPrefix(c, w) {\n                results = append(results, c)\n                matchFound = true\n                break\n            }\n        }\n        if !matchFound {\n            results = append(results, \"*error*\")\n        }\n    }\n    return results\n}\n\nfunc main() {\n    table = strings.TrimSpace(table)\n    commands := strings.Fields(table)\n    clen := len(commands)\n    minLens := make([]int, clen)\n    for i := 0; i < clen; i++ {\n        count := 0\n        for _, c := range commands[i] {\n            if c >= 'A' && c <= 'Z' {\n                count++\n            }\n        }\n        minLens[i] = count\n    }\n    sentence :=  \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n    words := strings.Fields(sentence)\n    results := validate(commands, words, minLens)\n    fmt.Print(\"user words:  \")\n    for j := 0; j < len(words); j++ {\n        fmt.Printf(\"%-*s \", len(results[j]), words[j])\n    }\n    fmt.Print(\"\\nfull words:  \")\n    fmt.Println(strings.Join(results, \" \"))\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy \"\n  \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n  \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n  \"Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO \"\n  \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT \"\n  \"READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT \"\n  \"RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nsize_t get_min_length(const char* str, size_t n) {\n    size_t len = 0;\n    while (len < n && isupper((unsigned char)str[len]))\n        ++len;\n    return len;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = get_min_length(word, word_len);\n        new_cmd->cmd = uppercase(word, word_len);\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 45591, "name": "Enforced immutability", "Go": "package main\n\nfunc main() {\n    s := \"immutable\"\n    s[0] = 'a'\n}\n", "C": "#define PI      3.14159265358979323\n#define MINSIZE 10\n#define MAXSIZE 100\n"}
{"id": 45592, "name": "Sutherland-Hodgman polygon clipping", "Go": "package main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 / (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) / dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)/sizeof(vec_t))\n#define slen (sizeof(s)/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"/l {lineto} def /m{moveto} def /s{setrgbcolor} def\"\n\t\t\"/c {closepath} def /gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n"}
{"id": 45593, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 45594, "name": "Bacon cipher", "Go": "package main\n\nimport(\n    \"fmt\"\n    \"strings\"\n)\n\nvar codes = map[rune]string {\n    'a' : \"AAAAA\", 'b' : \"AAAAB\", 'c' : \"AAABA\", 'd' : \"AAABB\", 'e' : \"AABAA\",\n    'f' : \"AABAB\", 'g' : \"AABBA\", 'h' : \"AABBB\", 'i' : \"ABAAA\", 'j' : \"ABAAB\",\n    'k' : \"ABABA\", 'l' : \"ABABB\", 'm' : \"ABBAA\", 'n' : \"ABBAB\", 'o' : \"ABBBA\",\n    'p' : \"ABBBB\", 'q' : \"BAAAA\", 'r' : \"BAAAB\", 's' : \"BAABA\", 't' : \"BAABB\",\n    'u' : \"BABAA\", 'v' : \"BABAB\", 'w' : \"BABBA\", 'x' : \"BABBB\", 'y' : \"BBAAA\",\n    'z' : \"BBAAB\", ' ' : \"BBBAA\",  \n}\n\nfunc baconEncode(plainText string, message string) string {\n    pt := strings.ToLower(plainText)\n    var sb []byte\n    for _, c := range pt {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, codes[c]...)\n        } else {\n            sb = append(sb, codes[' ']...)\n        }\n    }\n    et := string(sb)\n    mg := strings.ToLower(message)  \n    sb = nil  \n    var count = 0\n    for _, c := range mg {\n        if c >= 'a' && c <= 'z' {\n            if et[count] == 'A' {\n                sb = append(sb, byte(c))\n            } else {\n                sb = append(sb, byte(c - 32))  \n            }\n            count++\n            if count == len(et) { break }\n        } else {\n            sb = append(sb, byte(c))\n        }\n    }\n    return string(sb)\n}\n\nfunc baconDecode(message string) string {\n    var sb []byte\n    for _, c := range message {\n        if c >= 'a' && c <= 'z' {\n            sb = append(sb, 'A')\n        } else if c >= 'A' && c <= 'Z' {\n            sb = append(sb, 'B')\n        }\n    }\n    et := string(sb)\n    sb = nil  \n    for i := 0; i < len(et); i += 5 {\n        quintet := et[i : i + 5]\n        for k, v := range codes {\n            if v == quintet {\n                sb = append(sb, byte(k))\n                break\n            }\n        }\n    }\n    return string(sb)\n} \n\nfunc main() {\n    plainText := \"the quick brown fox jumps over the lazy dog\"\n    message := \"bacon's cipher is a method of steganography created by francis bacon.\" +\n        \"this task is to implement a program for encryption and decryption of \" +\n        \"plaintext using the simple alphabet of the baconian cipher or some \" +\n        \"other kind of representation of this alphabet (make anything signify anything). \" +\n        \"the baconian alphabet may optionally be extended to encode all lower \" +\n        \"case characters individually and/or adding a few punctuation characters \" +\n        \"such as the space.\"\n    cipherText := baconEncode(plainText, message)\n    fmt.Printf(\"Cipher text ->\\n\\n%s\\n\", cipherText)\n    decodedText := baconDecode(cipherText)\n    fmt.Printf(\"\\nHidden text ->\\n\\n%s\\n\", decodedText)\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar *codes[] = {\n    \"AAAAA\", \"AAAAB\", \"AAABA\", \"AAABB\", \"AABAA\",\n    \"AABAB\", \"AABBA\", \"AABBB\", \"ABAAA\", \"ABAAB\",\n    \"ABABA\", \"ABABB\", \"ABBAA\", \"ABBAB\", \"ABBBA\",\n    \"ABBBB\", \"BAAAA\", \"BAAAB\", \"BAABA\", \"BAABB\",\n    \"BABAA\", \"BABAB\", \"BABBA\", \"BABBB\", \"BBAAA\",\n    \"BBAAB\", \"BBBAA\"\n};\n\nchar *get_code(const char c) {\n    if (c >= 97 && c <= 122) return codes[c - 97];\n    return codes[26];\n}\n\nchar get_char(const char *code) {\n    int i;\n    if (!strcmp(codes[26], code)) return ' ';\n    for (i = 0; i < 26; ++i) {\n        if (strcmp(codes[i], code) == 0) return 97 + i;\n    }\n    printf(\"\\nCode \\\"%s\\\" is invalid\\n\", code);\n    exit(1);\n}\n\nvoid str_tolower(char s[]) {\n    int i;\n    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);\n}\n\nchar *bacon_encode(char plain_text[], char message[]) {\n    int i, count;\n    int plen = strlen(plain_text), mlen = strlen(message);\n    int elen = 5 * plen;\n    char c;\n    char *p, *et, *mt;\n    et = malloc(elen + 1);  \n    str_tolower(plain_text);\n    for (i = 0, p = et; i < plen; ++i, p += 5) {\n        c = plain_text[i];\n        strncpy(p, get_code(c), 5);\n    }\n    *++p = '\\0';\n\n    \n    str_tolower(message);\n    mt = calloc(mlen + 1, 1);\n    for (i = 0, count = 0; i < mlen; ++i) {\n        c = message[i];\n        if (c >= 'a' && c <= 'z') {\n            if (et[count] == 'A')\n                mt[i] = c;\n            else\n                mt[i] = c - 32;  \n            if (++count == elen) break;\n        }\n        else mt[i] = c;\n    }\n    free(et);     \n    return mt;\n}\n\nchar *bacon_decode(char cipher_text[]) {\n    int i, count, clen = strlen(cipher_text);\n    int plen;\n    char *p, *ct, *pt;\n    char c, quintet[6];\n    ct = calloc(clen + 1, 1);\n    for (i = 0, count = 0; i < clen; ++i) {\n        c = cipher_text[i];\n        if (c >= 'a' && c <= 'z')\n            ct[count++] = 'A';\n        else if (c >= 'A' && c <= 'Z')\n            ct[count++] = 'B';\n    }\n\n    plen = strlen(ct) / 5; \n    pt = malloc(plen + 1);\n    for (i = 0, p = ct; i < plen; ++i, p += 5) {\n        strncpy(quintet, p, 5);\n        quintet[5] = '\\0';\n        pt[i] = get_char(quintet);\n    }\n    pt[plen] = '\\0';\n    free(ct);\n    return pt;\n} \n\nint main() {\n    char plain_text[] = \"the quick brown fox jumps over the lazy dog\";\n    char message[] = \"bacon's cipher is a method of steganography created by francis bacon.\"\n        \"this task is to implement a program for encryption and decryption of \"\n        \"plaintext using the simple alphabet of the baconian cipher or some \"\n        \"other kind of representation of this alphabet (make anything signify anything). \"\n        \"the baconian alphabet may optionally be extended to encode all lower \"\n        \"case characters individually and/or adding a few punctuation characters \"\n        \"such as the space.\";\n    char *cipher_text, *hidden_text;\n    cipher_text = bacon_encode(plain_text, message);\n    printf(\"Cipher text ->\\n\\n%s\\n\", cipher_text);\n    hidden_text = bacon_decode(cipher_text);\n    printf(\"\\nHidden text ->\\n\\n%s\\n\", hidden_text);\n    free(cipher_text);\n    free(hidden_text);\n    return 0;\n}\n"}
{"id": 45595, "name": "Spiral matrix", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar n = 5\n\nfunc main() {\n    if n < 1 {\n        return\n    }\n    top, left, bottom, right := 0, 0, n-1, n-1\n    sz := n * n\n    a := make([]int, sz)\n    i := 0\n    for left < right {\n        \n        for c := left; c <= right; c++ {\n            a[top*n+c] = i\n            i++\n        }\n        top++\n        \n        for r := top; r <= bottom; r++ {\n            a[r*n+right] = i\n            i++\n        }\n        right--\n        if top == bottom {\n            break\n        }\n        \n        for c := right; c >= left; c-- {\n            a[bottom*n+c] = i\n            i++\n        }\n        bottom--\n        \n        for r := bottom; r >= top; r-- {\n            a[r*n+left] = i\n            i++\n        }\n        left++\n    }\n    \n    a[top*n+left] = i\n\n    \n    w := len(strconv.Itoa(n*n - 1))\n    for i, e := range a {\n        fmt.Printf(\"%*d \", w, e)\n        if i%n == n-1 {\n            fmt.Println(\"\")\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n \n#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]\nint main(int c, char **v)\n{\n\tint i, j, m = 0, n = 0;\n \n\t\n\tif (c >= 2) m = atoi(v[1]);\n\tif (c >= 3) n = atoi(v[2]);\n\tif (m <= 0) m = 5;\n\tif (n <= 0) n = m;\n \n\tint **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);\n\ts[0] = (int*)(s + m);\n\tfor (i = 1; i < m; i++) s[i] = s[i - 1] + n;\n \n\tint dx = 1, dy = 0, val = 0, t;\n\tfor (i = j = 0; valid(i, j); i += dy, j += dx ) {\n\t\tfor (; valid(i, j); j += dx, i += dy)\n\t\t\ts[i][j] = ++val;\n \n\t\tj -= dx; i -= dy;\n\t\tt = dy; dy = dx; dx = -t;\n\t}\n\n\tfor (t = 2; val /= 10; t++);\n\n\tfor(i = 0; i < m; i++)\n\t\tfor(j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tprintf(\"%*d\", t, s[i][j]);\n\n\treturn 0;\n}\n"}
{"id": 45596, "name": "Optional parameters", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n"}
{"id": 45597, "name": "Optional parameters", "Go": "type cell string\n\ntype spec struct {\n    less     func(cell, cell) bool\n    column   int\n    reverse  bool\n}\n\nfunc newSpec() (s spec) {\n    \n    return\n}\n\n\nt.sort(newSpec())\n\n\ns := newSpec\ns.reverse = true\nt.sort(s)\n", "C": "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\ntypedef const char * String;\ntypedef struct sTable {\n    String * *rows;\n    int      n_rows,n_cols;\n} *Table;\n\ntypedef int (*CompareFctn)(String a, String b);\n\nstruct {\n   CompareFctn  compare;\n   int   column;\n   int   reversed;\n} sortSpec;\n\nint CmprRows( const void *aa, const void *bb)\n{\n   String *rA = *(String *const *)aa;\n   String *rB = *(String *const *)bb;\n   int sortCol = sortSpec.column;\n\n   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];\n   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];\n   return sortSpec.compare( left, right );\n}\n\n\nint sortTable(Table tbl, const char* argSpec,... )\n{\n   va_list vl;\n   const char *p;\n   int c;\n   sortSpec.compare = &strcmp;\n   sortSpec.column = 0;\n   sortSpec.reversed = 0;\n\n   va_start(vl, argSpec);\n   if (argSpec)\n      for (p=argSpec; *p; p++) {\n         switch (*p) {\n         case 'o':\n            sortSpec.compare = va_arg(vl,CompareFctn);\n            break;\n         case 'c':\n            c = va_arg(vl,int);\n            if ( 0<=c && c<tbl->n_cols)\n               sortSpec.column  = c;\n            break;\n         case 'r':\n            sortSpec.reversed = (0!=va_arg(vl,int));\n            break;\n         }\n      }\n   va_end(vl);\n   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);\n   return 0;\n}\n\nvoid printTable( Table tbl, FILE *fout, const char *colFmts[])\n{\n   int row, col;\n\n   for (row=0; row<tbl->n_rows; row++) {\n      fprintf(fout, \"   \");\n      for(col=0; col<tbl->n_cols; col++) {\n         fprintf(fout, colFmts[col], tbl->rows[row][col]);\n      }\n      fprintf(fout, \"\\n\");\n   }\n   fprintf(fout, \"\\n\");\n}\n\nint ord(char v)\n{\n    return v-'0';\n}\n\n\nint cmprStrgs(String s1, String s2)\n{\n    const char *p1 = s1; \n    const char *p2 = s2;\n    const char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) {\n       p1++; p2++;\n    }\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint main()\n{\n   const char *colFmts[] = {\" %-5.5s\",\" %-5.5s\",\" %-9.9s\"};\n   String r1[] = { \"a101\", \"red\",  \"Java\" };\n   String r2[] = { \"ab40\", \"gren\", \"Smalltalk\" };\n   String r3[] = { \"ab9\",  \"blue\", \"Fortran\" };\n   String r4[] = { \"ab09\", \"ylow\", \"Python\" };\n   String r5[] = { \"ab1a\", \"blak\", \"Factor\" };\n   String r6[] = { \"ab1b\", \"brwn\", \"C Sharp\" };\n   String r7[] = { \"Ab1b\", \"pink\", \"Ruby\" };\n   String r8[] = { \"ab1\",  \"orng\", \"Scheme\" };\n\n   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };\n   struct sTable table;\n   table.rows = rows;\n   table.n_rows = 8;\n   table.n_cols = 3;\n\n   sortTable(&table, \"\");\n   printf(\"sort on col 0, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"ro\", 1, &cmprStrgs);\n   printf(\"sort on col 0, reverse.special\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"c\", 1);\n   printf(\"sort on col 1, ascending\\n\");\n   printTable(&table, stdout, colFmts);\n\n   sortTable(&table, \"cr\", 2, 1);\n   printf(\"sort on col 2, reverse\\n\");\n   printTable(&table, stdout, colFmts);\n   return 0;\n}\n"}
{"id": 45598, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 45599, "name": "Voronoi diagram", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image/color\"\n    \"image/draw\"\n    \"image/png\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nconst (\n    imageWidth  = 300\n    imageHeight = 200\n    nSites      = 10\n)\n\nfunc main() {\n    writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n    \n    sc := make([]color.NRGBA, nSites)\n    for i := range sx {\n        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n            uint8(rand.Intn(256)), 255}\n    }\n\n    \n    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n    for x := 0; x < imageWidth; x++ {\n        for y := 0; y < imageHeight; y++ {\n            dMin := dot(imageWidth, imageHeight)\n            var sMin int\n            for s := 0; s < nSites; s++ {\n                if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n                    sMin = s\n                    dMin = d\n                }\n            }\n            img.SetNRGBA(x, y, sc[sMin])\n        }\n    }\n    \n    black := image.NewUniform(color.Black)\n    for s := 0; s < nSites; s++ {\n        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n            black, image.ZP, draw.Src)\n    }\n    return img\n}\n\nfunc dot(x, y int) int {\n    return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n    rand.Seed(time.Now().Unix())\n    sx = make([]int, nSites)\n    sy = make([]int, nSites)\n    for i := range sx {\n        sx[i] = rand.Intn(imageWidth)\n        sy[i] = rand.Intn(imageHeight)\n    }\n    return\n}\n\nfunc writePngFile(img image.Image) {\n    f, err := os.Create(\"voronoi.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 \nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n"}
{"id": 45600, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n"}
{"id": 45601, "name": "Call a foreign-language function", "Go": "package main\n\n\n\nimport \"C\"\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    \n    go1 := \"hello C\"\n    \n    c1 := C.CString(go1)\n    \n    go1 = \"\"\n    \n    c2 := C.strdup(c1)\n    \n    C.free(unsafe.Pointer(c1))\n    \n    go2 := C.GoString(c2)\n    \n    C.free(unsafe.Pointer(c2))\n    \n    fmt.Println(go2)\n}\n", "C": "\n\n\n\n#include <stdio.h>\n\nvoid sayHello(char* name){\n    printf(\"Hello %s!\\n\", name);\n}\n\nint doubleNum(int num){\n    return num * 2;\n}\n"}
{"id": 45602, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 45603, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 45604, "name": "Knuth's algorithm S", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n    s := make([]byte, 0, n)\n    m := n\n    return func(item byte) []byte {\n        if len(s) < n {\n            s = append(s, item)\n        } else {\n            m++\n            if rand.Intn(m) < n {\n                s[rand.Intn(n)] = item\n            }\n        }\n        return s\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    var freq [10]int\n    for r := 0; r < 1e5; r++ {\n        sOfN := sOfNCreator(3)\n        for d := byte('0'); d < '9'; d++ {\n            sOfN(d)\n        }\n        for _, d := range sOfN('9') {\n            freq[d-'0']++\n        }\n    }\n    fmt.Println(freq)\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nstruct s_env {\n    unsigned int n, i;\n    size_t size;\n    void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n    s_env->i = 0;\n    s_env->n = n;\n    s_env->size = size;\n    s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n    memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n    s_env->i++;\n    if (s_env->i <= s_env->n)\n        sample_set_i(s_env, s_env->i - 1, item);\n    else if ((rand() % s_env->i) < s_env->n)\n        sample_set_i(s_env, rand() % s_env->n, item);\n    return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n    int i;\n    struct s_env s_env;\n    s_of_n_init(&s_env, sizeof(items_set[0]), n);\n    for (i = 0; i < num_items; i++) {\n        s_of_n(&s_env, (void *) &items_set[i]);\n    }\n    return (int *)s_env.sample;\n}\n\nint main()\n{\n    unsigned int i, j;\n    unsigned int n = 3;\n    unsigned int num_items = 10;\n    unsigned int *frequencies;\n    int *items_set;\n    srand(time(NULL));\n    items_set = malloc(num_items * sizeof(int));\n    frequencies = malloc(num_items * sizeof(int));\n    for (i = 0; i < num_items; i++) {\n        items_set[i] = i;\n        frequencies[i] = 0;\n    }\n    for (i = 0; i < 100000; i++) {\n        int *res = test(n, items_set, num_items);\n        for (j = 0; j < n; j++) {\n            frequencies[res[j]]++;\n        }\n\tfree(res);\n    }\n    for (i = 0; i < num_items; i++) {\n        printf(\" %d\", frequencies[i]);\n    }\n    puts(\"\");\n    return 0;\n}\n"}
{"id": 45605, "name": "Faulhaber's triangle", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc bernoulli(n uint) *big.Rat {\n    a := make([]big.Rat, n+1)\n    z := new(big.Rat)\n    for m := range a {\n        a[m].SetFrac64(1, int64(m+1))\n        for j := m; j >= 1; j-- {\n            d := &a[j-1]\n            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))\n        }\n    }\n    \n    if n != 1 {\n        return &a[0]\n    }\n    a[0].Neg(&a[0])\n    return &a[0]\n}\n\nfunc binomial(n, k int) int64 {\n    if n <= 0 || k <= 0 || n < k {\n        return 1\n    }\n    var num, den int64 = 1, 1\n    for i := k + 1; i <= n; i++ {\n        num *= int64(i)\n    }\n    for i := 2; i <= n-k; i++ {\n        den *= int64(i)\n    }\n    return num / den\n}\n\nfunc faulhaberTriangle(p int) []big.Rat {\n    coeffs := make([]big.Rat, p+1)\n    q := big.NewRat(1, int64(p)+1)\n    t := new(big.Rat)\n    u := new(big.Rat)\n    sign := -1\n    for j := range coeffs {\n        sign *= -1\n        d := &coeffs[p-j]\n        t.SetInt64(int64(sign))\n        u.SetInt64(binomial(p+1, j))\n        d.Mul(q, t)\n        d.Mul(d, u)\n        d.Mul(d, bernoulli(uint(j)))\n    }\n    return coeffs\n}\n\nfunc main() {\n    for i := 0; i < 10; i++ {\n        coeffs := faulhaberTriangle(i)\n        for _, coeff := range coeffs {\n            fmt.Printf(\"%5s  \", coeff.RatString())\n        }\n        fmt.Println()\n    }\n    fmt.Println()\n    \n    k := 17\n    cc := faulhaberTriangle(k)\n    n := int64(1000)\n    nn := big.NewRat(n, 1)\n    np := big.NewRat(1, 1)\n    sum := new(big.Rat)\n    tmp := new(big.Rat)\n    for _, c := range cc {\n        np.Mul(np, nn)\n        tmp.Set(np)\n        tmp.Mul(tmp, &c)\n        sum.Add(sum, tmp)\n    }\n    fmt.Println(sum.RatString())\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint binomial(int n, int k) {\n    int num, denom, i;\n\n    if (n < 0 || k < 0 || n < k) return -1;\n    if (n == 0 || k == 0) return 1;\n\n    num = 1;\n    for (i = k + 1; i <= n; ++i) {\n        num = num * i;\n    }\n\n    denom = 1;\n    for (i = 2; i <= n - k; ++i) {\n        denom *= i;\n    }\n\n    return num / denom;\n}\n\nint gcd(int a, int b) {\n    int temp;\n    while (b != 0) {\n        temp = a % b;\n        a = b;\n        b = temp;\n    }\n    return a;\n}\n\ntypedef struct tFrac {\n    int num, denom;\n} Frac;\n\nFrac makeFrac(int n, int d) {\n    Frac result;\n    int g;\n\n    if (d == 0) {\n        result.num = 0;\n        result.denom = 0;\n        return result;\n    }\n\n    if (n == 0) {\n        d = 1;\n    } else if (d < 0) {\n        n = -n;\n        d = -d;\n    }\n\n    g = abs(gcd(n, d));\n    if (g > 1) {\n        n = n / g;\n        d = d / g;\n    }\n\n    result.num = n;\n    result.denom = d;\n    return result;\n}\n\nFrac negateFrac(Frac f) {\n    return makeFrac(-f.num, f.denom);\n}\n\nFrac subFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);\n}\n\nFrac multFrac(Frac lhs, Frac rhs) {\n    return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);\n}\n\nbool equalFrac(Frac lhs, Frac rhs) {\n    return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);\n}\n\nbool lessFrac(Frac lhs, Frac rhs) {\n    return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);\n}\n\nvoid printFrac(Frac f) {\n    char buffer[7];\n    int len;\n\n    if (f.denom != 1) {\n        snprintf(buffer, 7, \"%d/%d\", f.num, f.denom);\n    } else {\n        snprintf(buffer, 7, \"%d\", f.num);\n    }\n\n    len = 7 - strlen(buffer);\n    while (len-- > 0) {\n        putc(' ', stdout);\n    }\n\n    printf(buffer);\n}\n\nFrac bernoulli(int n) {\n    Frac a[16];\n    int j, m;\n\n    if (n < 0) {\n        a[0].num = 0;\n        a[0].denom = 0;\n        return a[0];\n    }\n\n    for (m = 0; m <= n; ++m) {\n        a[m] = makeFrac(1, m + 1);\n        for (j = m; j >= 1; --j) {\n            a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));\n        }\n    }\n\n    if (n != 1) {\n        return a[0];\n    }\n\n    return negateFrac(a[0]);\n}\n\nvoid faulhaber(int p) {\n    Frac q, *coeffs;\n    int j, sign;\n\n    coeffs = malloc(sizeof(Frac)*(p + 1));\n\n    q = makeFrac(1, p + 1);\n    sign = -1;\n    for (j = 0; j <= p; ++j) {\n        sign = -1 * sign;\n        coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));\n    }\n\n    for (j = 0; j <= p; ++j) {\n        printFrac(coeffs[j]);\n    }\n    printf(\"\\n\");\n\n    free(coeffs);\n}\n\nint main() {\n    int i;\n\n    for (i = 0; i < 10; ++i) {\n        faulhaber(i);\n    }\n\n    return 0;\n}\n"}
{"id": 45606, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 45607, "name": "Command-line arguments", "Go": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 45608, "name": "Word wheel", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"sort\"\n    \"strings\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"unixdict.txt\")\n    if err != nil {\n        log.Fatal(\"Error reading file\")\n    }\n    letters := \"deegklnow\"\n    wordsAll := bytes.Split(b, []byte{'\\n'})\n    \n    var words [][]byte\n    for _, word := range wordsAll {\n        word = bytes.TrimSpace(word)\n        le := len(word)\n        if le > 2 && le < 10 {\n            words = append(words, word)\n        }\n    }\n    var found []string\n    for _, word := range words {\n        le := len(word)\n        if bytes.IndexByte(word, 'k') >= 0 {\n            lets := letters\n            ok := true\n            for i := 0; i < le; i++ {\n                c := word[i]\n                ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                if ix < len(lets) && lets[ix] == c {\n                    lets = lets[0:ix] + lets[ix+1:]\n                } else {\n                    ok = false\n                    break\n                }\n            }\n            if ok {\n                found = append(found, string(word))\n            }\n        }\n    }\n    fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n    fmt.Println(strings.Join(found, \"\\n\"))\n\n    \n    mostFound := 0\n    var mostWords9 []string\n    var mostLetters []byte\n    \n    var words9 [][]byte\n    for _, word := range words {\n        if len(word) == 9 {\n            words9 = append(words9, word)\n        }\n    }\n    \n    for _, word9 := range words9 {\n        letterBytes := make([]byte, len(word9))\n        copy(letterBytes, word9)\n        sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n        \n        distinctBytes := []byte{letterBytes[0]}\n        for _, b := range letterBytes[1:] {\n            if b != distinctBytes[len(distinctBytes)-1] {\n                distinctBytes = append(distinctBytes, b)\n            }\n        }\n        distinctLetters := string(distinctBytes)\n        for _, letter := range distinctLetters {\n            found := 0\n            letterByte := byte(letter)\n            for _, word := range words {\n                le := len(word)\n                if bytes.IndexByte(word, letterByte) >= 0 {\n                    lets := string(letterBytes)\n                    ok := true\n                    for i := 0; i < le; i++ {\n                        c := word[i]\n                        ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n                        if ix < len(lets) && lets[ix] == c {\n                            lets = lets[0:ix] + lets[ix+1:]\n                        } else {\n                            ok = false\n                            break\n                        }\n                    }\n                    if ok {\n                        found = found + 1\n                    }\n                }\n            }\n            if found > mostFound {\n                mostFound = found\n                mostWords9 = []string{string(word9)}\n                mostLetters = []byte{letterByte}\n            } else if found == mostFound {\n                mostWords9 = append(mostWords9, string(word9))\n                mostLetters = append(mostLetters, letterByte)\n            }\n        }\n    }\n    fmt.Println(\"\\nMost words found =\", mostFound)\n    fmt.Println(\"Nine letter words producing this total:\")\n    for i := 0; i < len(mostWords9); i++ {\n        fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n    }\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n    int max_count[LETTERS] = { 0 };\n    for (const char* p = letters; *p; ++p) {\n        char c = *p;\n        if (is_letter(c))\n            ++max_count[index(c)];\n    }\n    char word[MAX_WORD + 1] = { 0 };\n    while (fgets(word, MAX_WORD, dict)) {\n        int count[LETTERS] = { 0 };\n        for (const char* p = word; *p; ++p) {\n            char c = *p;\n            if (c == '\\n') {\n                if (p >= word + min_length && count[index(central)] > 0)\n                    printf(\"%s\", word);\n            } else if (is_letter(c)) {\n                int i = index(c);\n                if (++count[i] > max_count[i]) {\n                    break;\n                }\n            } else {\n                break;\n            }\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n    FILE* in = fopen(dict, \"r\");\n    if (in == NULL) {\n        perror(dict);\n        return 1;\n    }\n    word_wheel(\"ndeokgelw\", 'k', 3, in);\n    fclose(in);\n    return 0;\n}\n"}
{"id": 45609, "name": "Array concatenation", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    \n    \n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \n    c := append(a, b...)\n    fmt.Println(c)\n\n    \n    \n    \n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \n    fmt.Println(k)\n\n    \n    \n    \n    \n    \n    \n    \n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n"}
{"id": 45610, "name": "User input_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var s string\n    var i int\n    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {\n        fmt.Println(\"good\")\n    } else {\n        fmt.Println(\"wrong\")\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n    \n    char str[BUFSIZ];\n    puts(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    \n    long num;\n    char buf[BUFSIZ];\n    do\n    {\n        puts(\"Enter 75000: \");\n        fgets(buf, sizeof(buf), stdin);\n        num = strtol(buf, NULL, 10);\n    } while (num != 75000);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45611, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 45612, "name": "Musical scale", "Go": "package main\n\nimport (\n    \"encoding/binary\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    const (\n        sampleRate = 44100\n        duration   = 8\n        dataLength = sampleRate * duration\n        hdrSize    = 44\n        fileLen    = dataLength + hdrSize - 8\n    )\n\n    \n    buf1 := make([]byte, 1)\n    buf2 := make([]byte, 2)\n    buf4 := make([]byte, 4)\n\n    \n    var sb strings.Builder\n    sb.WriteString(\"RIFF\")\n    binary.LittleEndian.PutUint32(buf4, fileLen)\n    sb.Write(buf4) \n    sb.WriteString(\"WAVE\")\n    sb.WriteString(\"fmt \")\n    binary.LittleEndian.PutUint32(buf4, 16)\n    sb.Write(buf4) \n    binary.LittleEndian.PutUint16(buf2, 1)\n    sb.Write(buf2) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint32(buf4, sampleRate)\n    sb.Write(buf4) \n    sb.Write(buf4) \n    sb.Write(buf2) \n    binary.LittleEndian.PutUint16(buf2, 8)\n    sb.Write(buf2) \n    sb.WriteString(\"data\")\n    binary.LittleEndian.PutUint32(buf4, dataLength)\n    sb.Write(buf4) \n    wavhdr := []byte(sb.String())\n\n    \n    f, err := os.Create(\"notes.wav\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer f.Close()\n    f.Write(wavhdr)\n\n    \n    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n    for j := 0; j < duration; j++ {\n        freq := freqs[j]\n        omega := 2 * math.Pi * freq\n        for i := 0; i < dataLength/duration; i++ {\n            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n            buf1[0] = byte(math.Round(y))\n            f.Write(buf1)\n        }\n    }\n}\n", "C": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<dos.h>\n\ntypedef struct{\n\tchar str[3];\n\tint key;\n\t}note;\n\t\nnote sequence[] = {{\"Do\",0},{\"Re\",2},{\"Mi\",4},{\"Fa\",5},{\"So\",7},{\"La\",9},{\"Ti\",11},{\"Do\",12}};\n\nint main(void)\n{\n\tint i=0;\n\t\n\twhile(!kbhit())\n\t{\n\t\tprintf(\"\\t%s\",sequence[i].str);\n\t\tsound(261.63*pow(2,sequence[i].key/12.0));\n\t\tdelay(sequence[i].key%12==0?500:1000);\n\t\ti = (i+1)%8;\n\t\ti==0?printf(\"\\n\"):printf(\"\");\n\t}\n\tnosound();\n\treturn 0;\n}\n"}
{"id": 45613, "name": "Knapsack problem_0-1", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) / sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n"}
{"id": 45614, "name": "Primes - allocate descendants to their ancestors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getPrimes(max int) []int {\n    if max < 2 {\n        return []int{}\n    }\n    lprimes := []int{2}\nouter:\n    for x := 3; x <= max; x += 2 {\n        for _, p := range lprimes {\n            if x%p == 0 {\n                continue outer\n            }\n        }\n        lprimes = append(lprimes, x)\n    }\n    return lprimes\n}\n\nfunc main() {\n    const maxSum = 99\n    descendants := make([][]int64, maxSum+1)\n    ancestors := make([][]int, maxSum+1)\n    for i := 0; i <= maxSum; i++ {\n        descendants[i] = []int64{}\n        ancestors[i] = []int{}\n    }\n    primes := getPrimes(maxSum)\n\n    for _, p := range primes {\n        descendants[p] = append(descendants[p], int64(p))\n        for s := 1; s < len(descendants)-p; s++ {\n            temp := make([]int64, len(descendants[s]))\n            for i := 0; i < len(descendants[s]); i++ {\n                temp[i] = int64(p) * descendants[s][i]\n            }\n            descendants[s+p] = append(descendants[s+p], temp...)\n        }\n    }\n\n    for _, p := range append(primes, 4) {\n        le := len(descendants[p])\n        if le == 0 {\n            continue\n        }\n        descendants[p][le-1] = 0\n        descendants[p] = descendants[p][:le-1]\n    }\n    total := 0\n\n    for s := 1; s <= maxSum; s++ {\n        x := descendants[s]\n        sort.Slice(x, func(i, j int) bool {\n            return x[i] < x[j]\n        })\n        total += len(descendants[s])\n        index := 0\n        for ; index < len(descendants[s]); index++ {\n            if descendants[s][index] > int64(maxSum) {\n                break\n            }\n        }\n        for _, d := range descendants[s][:index] {\n            ancestors[d] = append(ancestors[s], s)\n        }\n        if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {\n            continue\n        }\n        temp := fmt.Sprintf(\"%v\", ancestors[s])\n        fmt.Printf(\"%2d: %d Ancestor(s): %-14s\", s, len(ancestors[s]), temp)\n        le := len(descendants[s])\n        if le <= 10 {\n            fmt.Printf(\"%5d Descendant(s): %v\\n\", le, descendants[s])\n        } else {\n            fmt.Printf(\"%5d Descendant(s): %v\\b ...]\\n\", le, descendants[s][:10])\n        }\n    }\n    fmt.Println(\"\\nTotal descendants\", total)\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXPRIME 99\t\t\t\t\t\t\n#define MAXPARENT 99\t\t\t\t\t\n#define NBRPRIMES 30\t\t\t\t\t\n#define NBRANCESTORS 10\t\t\t\t\t\n\nFILE *FileOut;\nchar format[] = \", %lld\";\n\nint Primes[NBRPRIMES];\t\t\t\t\t\nint iPrimes;\t\t\t\t\t\t\t\n\nshort Ancestors[NBRANCESTORS];\t\t\t\n\nstruct Children {\n\tlong long Child;\n\tstruct Children *pNext;\n};\nstruct Children *Parents[MAXPARENT+1][2];\t\nint CptDescendants[MAXPARENT+1];\t\t\t\nlong long MaxDescendant = (long long) pow(3.0, 33.0);\t\n\nshort GetParent(long long child);\nstruct Children *AppendChild(struct Children *node, long long child);\nshort GetAncestors(short child);\nvoid PrintDescendants(struct Children *node);\nint GetPrimes(int primes[], int maxPrime);\n\nint main()\n{\n\tlong long Child;\n\tshort i, Parent, Level;\n\tint TotDesc = 0;\n\t\n\tif ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)\n\t\treturn 1;\n\t\n\tfor (Child = 1; Child <= MaxDescendant; Child++)\n\t{\n\t\tif (Parent = GetParent(Child))\n\t\t{\n\t\t\tParents[Parent][1] = AppendChild(Parents[Parent][1], Child);\n\t\t\tif (Parents[Parent][0] == NULL)\n\t\t\t\tParents[Parent][0] = Parents[Parent][1];\n\t\t\tCptDescendants[Parent]++;\n\t\t}\n\t}\n\t\n\tif (MAXPARENT > MAXPRIME)\n\t\tif (GetPrimes(Primes, MAXPARENT) < 0)\n\t\t\treturn 1;\n\n\tif (fopen_s(&FileOut, \"Ancestors.txt\", \"w\"))\n\t\treturn 1;\n\n\tfor (Parent = 1; Parent <= MAXPARENT; Parent++)\n\t{\n\t\tLevel = GetAncestors(Parent);\n\t\t\n\t\tfprintf(FileOut, \"[%d] Level: %d\\n\", Parent, Level);\n\t\t\n\t\tif (Level)\n\t\t{\n\t\t\tfprintf(FileOut, \"Ancestors: %d\", Ancestors[0]);\n\t\t\t\n\t\t\tfor (i = 1; i < Level; i++)\n\t\t\t\tfprintf(FileOut, \", %d\", Ancestors[i]);\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"Ancestors: None\");\n\n\t\tif (CptDescendants[Parent])\n\t\t{\n\t\t\tfprintf(FileOut, \"\\nDescendants: %d\\n\", CptDescendants[Parent]);\n\t\t\tstrcpy_s(format, \"%lld\");\n\t\t\tPrintDescendants(Parents[Parent][0]);\n\t\t\tfprintf(FileOut, \"\\n\");\n\t\t}\n\t\telse\n\t\t\tfprintf(FileOut, \"\\nDescendants: None\\n\");\n\n\t\tfprintf(FileOut, \"\\n\");\n\t\tTotDesc += CptDescendants[Parent];\n\t}\n\n\tfprintf(FileOut, \"Total descendants %d\\n\\n\", TotDesc);\n\tif (fclose(FileOut))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nshort GetParent(long long child)\n{\n\tlong long Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1 && Parent <= MAXPARENT)\n\t{\n\t\tif (Index > iPrimes)\n\t\t\treturn 0;\n\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || Parent > MAXPARENT || child == 1)\n\t\treturn 0;\n\t\n\treturn Parent;\n}\n\nstruct Children *AppendChild(struct Children *node, long long child)\n{\n\tstatic struct Children *NodeNew;\n\t\n\tif (NodeNew = (struct Children *) malloc(sizeof(struct Children)))\n\t{\n\t\tNodeNew->Child = child;\n\t\tNodeNew->pNext = NULL;\n\t\tif (node != NULL)\n\t\t\tnode->pNext = NodeNew;\n\t}\n\t\n\treturn NodeNew;\n}\n\nshort GetAncestors(short child)\n{\n\tshort Child = child;\n\tshort Parent = 0;\n\tshort Index = 0;\n\t\n\twhile (Child > 1)\n\t{\n\t\twhile (Child % Primes[Index] == 0)\n\t\t{\n\t\t\tChild /= Primes[Index];\n\t\t\tParent += Primes[Index];\n\t\t}\n\t\t\n\t\tIndex++;\n\t}\n\t\n\tif (Parent == child || child == 1)\n\t\treturn 0;\n\t\n\tIndex = GetAncestors(Parent);\n\t\n\tAncestors[Index] = Parent;\n\treturn ++Index;\n}\n\nvoid PrintDescendants(struct Children *node)\n{\n\tstatic struct Children *NodeCurr;\n\tstatic struct Children *NodePrev;\n\n\tNodeCurr = node;\n\tNodePrev = NULL;\n\twhile (NodeCurr)\n\t{\n\t\tfprintf(FileOut, format, NodeCurr->Child);\n\t\tstrcpy_s(format, \", %lld\");\n\t\tNodePrev = NodeCurr;\n\t\tNodeCurr = NodeCurr->pNext;\n\t\tfree(NodePrev);\n\t}\n\n\treturn;\n}\n\nint GetPrimes(int primes[], int maxPrime)\n{\n\tif (maxPrime < 2)\n\t\treturn -1;\n\t\n\tint Index = 0, Value = 1;\n\tint Max, i;\n\n\tprimes[0] = 2;\n\n\twhile ((Value += 2) <= maxPrime)\n\t{\n\t\tMax = (int) floor(sqrt((double) Value));\n\t\t\n\t\tfor (i = 0; i <= Index; i++)\n\t\t{\n\t\t\tif (primes[i] > Max)\n\t\t\t{\n\t\t\t\tif (++Index >= NBRPRIMES)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tprimes[Index] = Value;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (Value % primes[i] == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Index;\n}\n"}
{"id": 45615, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 45616, "name": "Cartesian product of two or more lists", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n    p := make([]pair, len(a)*len(b))\n    i := 0\n    for _, a := range a {\n        for _, b := range b {\n            p[i] = pair{a, b}\n            i++\n        }\n    }\n    return p\n}\n\nfunc main() {\n    fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n    fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n    fmt.Println(cart2([]int{1, 2}, nil))\n    fmt.Println(cart2(nil, []int{1, 2}))\n}\n", "C": "#include<string.h>\n#include<stdlib.h>\n#include<stdio.h>\n\nvoid cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){\n\tint i,j;\n\t\n\tif(times==numSets){\n\t\tprintf(\"(\");\n\t\tfor(i=0;i<times;i++){\n\t\t\tprintf(\"%d,\",currentSet[i]);\n\t\t}\n\t\tprintf(\"\\b),\");\n\t}\n\telse{\n\t\tfor(j=0;j<setLengths[times];j++){\n\t\t\tcurrentSet[times] = sets[times][j];\n\t\t\tcartesianProduct(sets,setLengths,currentSet,numSets,times+1);\n\t\t}\n\t}\n}\n\nvoid printSets(int** sets, int* setLengths, int numSets){\n\tint i,j;\n\t\n\tprintf(\"\\nNumber of sets : %d\",numSets);\n\t\n\tfor(i=0;i<numSets+1;i++){\n\t\tprintf(\"\\nSet %d : \",i+1);\n\t\tfor(j=0;j<setLengths[i];j++){\n\t\t\tprintf(\" %d \",sets[i][j]);\n\t\t}\n\t}\n}\n\nvoid processInputString(char* str){\n\tint **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;\n\tchar *token,*holder,*holderToken;\n\t\n\tfor(i=0;str[i]!=00;i++)\n\t\tif(str[i]=='x')\n\t\t\tnumSets++;\n\t\t\n\tif(numSets==0){\n\t\t\tprintf(\"\\n%s\",str);\n\t\t\treturn;\n\t}\n\t\t\n\tcurrentSet = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsetLengths = (int*)calloc(sizeof(int),numSets + 1);\n\t\n\tsets = (int**)malloc((numSets + 1)*sizeof(int*));\n\t\n\ttoken = strtok(str,\"x\");\n\t\n\twhile(token!=NULL){\n\t\tholder = (char*)malloc(strlen(token)*sizeof(char));\n\t\t\n\t\tj = 0;\n\t\t\n\t\tfor(i=0;token[i]!=00;i++){\n\t\t\tif(token[i]>='0' && token[i]<='9')\n\t\t\t\tholder[j++] = token[i];\n\t\t\telse if(token[i]==',')\n\t\t\t\tholder[j++] = ' ';\n\t\t}\n\t\tholder[j] = 00;\n\t\t\n\t\tsetLength = 0;\n\t\t\n\t\tfor(i=0;holder[i]!=00;i++)\n\t\t\tif(holder[i]==' ')\n\t\t\t\tsetLength++;\n\t\t\t\n\t\tif(setLength==0 && strlen(holder)==0){\n\t\t\tprintf(\"\\n{}\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tsetLengths[counter] = setLength+1;\n\t\t\n\t\tsets[counter] = (int*)malloc((1+setLength)*sizeof(int));\n\t\t\n\t\tk = 0;\n\t\t\n\t\tstart = 0;\n\t\t\n\t\tfor(l=0;holder[l]!=00;l++){\n\t\t\tif(holder[l+1]==' '||holder[l+1]==00){\n\t\t\t\tholderToken = (char*)malloc((l+1-start)*sizeof(char));\n\t\t\t\tstrncpy(holderToken,holder + start,l+1-start);\n\t\t\t\tsets[counter][k++] = atoi(holderToken);\n\t\t\t\tstart = l+2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcounter++;\n\t\ttoken = strtok(NULL,\"x\");\n\t}\n\t\n\tprintf(\"\\n{\");\n\tcartesianProduct(sets,setLengths,currentSet,numSets + 1,0);\n\tprintf(\"\\b}\");\n\t\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage : %s <Set product expression enclosed in double quotes>\",argV[0]);\n\telse\n\t\tprocessInputString(argV[1]);\n\t\n\treturn 0;\n}\n"}
{"id": 45617, "name": "First-class functions", "Go": "package main\n\nimport \"math\"\nimport \"fmt\"\n\n\nfunc cube(x float64) float64 { return math.Pow(x, 3) }\n\n\ntype ffType func(float64) float64\n\nfunc compose(f, g ffType) ffType {\n    return func(x float64) float64 {\n        return f(g(x))\n    }\n}\n\nfunc main() {\n    \n    funclist := []ffType{math.Sin, math.Cos, cube}\n    \n    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}\n    for i := 0; i < 3; i++ {\n        \n        fmt.Println(compose(funclisti[i], funclist[i])(.5))\n    }\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n \n\ntypedef double (*Class2Func)(double);\n \n\ndouble functionA( double v)\n{\n   return v*v*v;\n}\ndouble functionB(double v)\n{\n   return exp(log(v)/3);\n}\n \n\ndouble Function1( Class2Func f2, double val )\n{\n    return f2(val);\n}\n \n\nClass2Func WhichFunc( int idx)\n{\n   return (idx < 4) ? &functionA : &functionB;\n}\n \n\nClass2Func funcListA[] = {&functionA, &sin, &cos, &tan };\nClass2Func funcListB[] = {&functionB, &asin, &acos, &atan };\n \n\ndouble InvokeComposed( Class2Func f1, Class2Func f2, double val )\n{\n   return f1(f2(val));\n}\n \ntypedef struct sComposition {\n   Class2Func f1;\n   Class2Func f2;\n} *Composition;\n \nComposition Compose( Class2Func f1, Class2Func f2)\n{\n   Composition comp = malloc(sizeof(struct sComposition));\n   comp->f1 = f1;\n   comp->f2 = f2;\n   return comp;\n}\n \ndouble CallComposed( Composition comp, double val )\n{\n    return comp->f1( comp->f2(val) );\n}\n\n \nint main(int argc, char *argv[])\n{\n   int ix;\n   Composition c;\n \n   printf(\"Function1(functionA, 3.0) = %f\\n\", Function1(WhichFunc(0), 3.0));\n \n   for (ix=0; ix<4; ix++) {\n       c = Compose(funcListA[ix], funcListB[ix]);\n       printf(\"Compostion %d(0.9) = %f\\n\", ix, CallComposed(c, 0.9));\n   }\n \n   return 0;\n}\n"}
{"id": 45618, "name": "Proper divisors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc listProperDivisors(limit int) {\n    if limit < 1 {\n        return\n    }\n    width := len(strconv.Itoa(limit))\n    for i := 1; i <= limit; i++ {\n        fmt.Printf(\"%*d -> \", width, i)\n        if i == 1 {\n            fmt.Println(\"(None)\")\n            continue\n        }\n        for j := 1; j <= i/2; j++ {\n            if i%j == 0 {\n                fmt.Printf(\" %d\", j)\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc countProperDivisors(n int) int {\n    if n < 2 {\n        return 0\n    }\n    count := 0\n    for i := 1; i <= n/2; i++ {\n        if n%i == 0 {\n            count++\n        }\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The proper divisors of the following numbers are :\\n\")\n    listProperDivisors(10)\n    fmt.Println()\n    maxCount := 0\n    most := []int{1}\n    for n := 2; n <= 20000; n++ {\n        count := countProperDivisors(n)\n        if count == maxCount {\n            most = append(most, n)\n        } else if count > maxCount {\n            maxCount = count\n            most = most[0:1]\n            most[0] = n\n        }\n    }\n    fmt.Print(\"The following number(s) <= 20000 have the most proper divisors, \")\n    fmt.Println(\"namely\", maxCount, \"\\b\\n\")\n    for _, n := range most {\n        fmt.Println(n)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdbool.h>\n\nint proper_divisors(const int n, bool print_flag)\n{\n    int count = 0;\n\n    for (int i = 1; i < n; ++i) {\n        if (n % i == 0) {\n            count++;\n            if (print_flag)\n                printf(\"%d \", i);\n        }\n    }\n\n    if (print_flag)\n        printf(\"\\n\");\n\n    return count;\n}\n\nint main(void)\n{\n    for (int i = 1; i <= 10; ++i) {\n        printf(\"%d: \", i);\n        proper_divisors(i, true);\n    }\n\n    int max = 0;\n    int max_i = 1;\n\n    for (int i = 1; i <= 20000; ++i) {\n        int v = proper_divisors(i, false);\n        if (v >= max) {\n            max = v;\n            max_i = i;\n        }\n    }\n\n    printf(\"%d with %d divisors\\n\", max_i, max);\n    return 0;\n}\n"}
{"id": 45619, "name": "XML_Output", "Go": "package main\n\nimport (\n    \"encoding/xml\"\n    \"fmt\"\n)\n\n\nfunc xRemarks(r CharacterRemarks) (string, error) {\n    b, err := xml.MarshalIndent(r, \"\", \"    \")\n    return string(b), err\n}\n\n\n\ntype CharacterRemarks struct {\n    Character []crm\n}\n\ntype crm struct {\n    Name   string `xml:\"name,attr\"`\n    Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n    x, err := xRemarks(CharacterRemarks{[]crm{\n        {`April`, `Bubbly: I'm > Tam and <= Emily`},\n        {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n        {`Emily`, `Short & shrift`},\n    }})\n    if err != nil {\n        x = err.Error()\n    }\n    fmt.Println(x)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n  \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n  \"Bubbly: I'm > Tam and <= Emily\",\n  \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n  \"Short & shrift\", NULL\n};\n\nint main()\n{\n  xmlDoc *doc = NULL;\n  xmlNode *root = NULL, *node;\n  const char **next;\n  int a;\n\n  doc = xmlNewDoc(\"1.0\");\n  root = xmlNewNode(NULL, \"CharacterRemarks\");\n  xmlDocSetRootElement(doc, root);\n\n  for(next = names, a = 0; *next != NULL; next++, a++) {\n    node = xmlNewNode(NULL, \"Character\");\n    (void)xmlNewProp(node, \"name\", *next);\n    xmlAddChild(node, xmlNewText(remarks[a]));\n    xmlAddChild(root, node);\n  }\n\n  xmlElemDump(stdout, doc, root);\n\n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n  \n  return EXIT_SUCCESS;\n}\n"}
{"id": 45620, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 45621, "name": "Plot coordinate pairs", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"log\"\n  \"os/exec\"\n)\n\nvar (\n  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n  g := exec.Command(\"gnuplot\", \"-persist\")\n  w, err := g.StdinPipe()\n  if err != nil {\n    log.Fatal(err)\n  }\n  if err = g.Start(); err != nil {\n    log.Fatal(err)\n  }\n  fmt.Fprintln(w, \"unset key; plot '-'\")\n  for i, xi := range x {\n    fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n  }\n  fmt.Fprintln(w, \"e\")\n  w.Close()\n  g.Wait()\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <plot.h>\n\n#define NP 10\ndouble x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\ndouble y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nvoid minmax(double *x, double *y,\n\t    double *minx, double *maxx, \n\t    double *miny, double *maxy, int n)\n{\n  int i;\n\n  *minx = *maxx = x[0];\n  *miny = *maxy = y[0];\n  for(i=1; i < n; i++) {\n    if ( x[i] < *minx ) *minx = x[i];\n    if ( x[i] > *maxx ) *maxx = x[i];\n    if ( y[i] < *miny ) *miny = y[i];\n    if ( y[i] > *maxy ) *maxy = y[i];\n  }\n}\n\n\n#define YLAB_HEIGHT_F 0.1\n#define XLAB_WIDTH_F 0.2  \n#define XDIV (NP*1.0)\n#define YDIV (NP*1.0)\n#define EXTRA_W 0.01\n#define EXTRA_H 0.01\n#define DOTSCALE (1.0/150.0)\n\n#define MAXLABLEN 32\n\n#define PUSHSCALE(X,Y) pl_fscale((X),(Y))\n#define POPSCALE(X,Y)  pl_fscale(1.0/(X), 1.0/(Y))\n#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)\n\nint main()\n{\n  int plotter, i;\n  double minx, miny, maxx, maxy;\n  double lx, ly;\n  double xticstep, yticstep, nx, ny;\n  double sx, sy;\n  \n  char labs[MAXLABLEN+1];\n\n  plotter = pl_newpl(\"png\", NULL, stdout, NULL);\n  if ( plotter < 0 ) exit(1);\n  pl_selectpl(plotter);\n  if ( pl_openpl() < 0 ) exit(1);\n\n  \n  minmax(x, y, &minx, &maxx, &miny, &maxy, NP);\n\n  lx = maxx - minx;\n  ly = maxy - miny;\n  pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,\n\t    ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);\n  \n  \n  xticstep = (ceil(maxx) - floor(minx)) / XDIV;\n  yticstep = (ceil(maxy) - floor(miny)) / YDIV;\n\n  pl_flinewidth(0.25);\n\n  \n  if ( lx < ly ) {\n    sx = lx/ly;\n    sy = 1.0;\n  } else {\n    sx = 1.0;\n    sy = ly/lx;\n  }\n\n  pl_erase();\n\n  \n  pl_fbox(floor(minx), floor(miny),\n\t  ceil(maxx), ceil(maxy));\n\n  \n  pl_fontname(\"HersheySerif\");\n  for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {\n    pl_fline(floor(minx), ny, ceil(maxx), ny);\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", ny);\n    FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);\n    PUSHSCALE(sx,sy);\n    pl_label(labs);\n    POPSCALE(sx,sy);\n  }\n  for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {\n    pl_fline(nx, floor(miny), nx, ceil(maxy));\n    snprintf(labs, MAXLABLEN, \"%6.2lf\", nx);\n    FMOVESCALE(nx, floor(miny));\n    PUSHSCALE(sx,sy);\n    pl_ftextangle(-90);\n    pl_alabel('l', 'b', labs);\n    POPSCALE(sx,sy);\n  }\n\n  \n  pl_fillcolorname(\"red\");\n  pl_filltype(1);\n  for(i=0; i < NP; i++)\n  {\n    pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,\n            x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);\n  }\n\n  pl_flushpl();\n  pl_closepl();\n}\n"}
{"id": 45622, "name": "Regular expressions", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n"}
{"id": 45623, "name": "Guess the number_With feedback (player)", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    lower, upper := 0, 100\n    fmt.Printf(`Instructions:\nThink of integer number from %d (inclusive) to %d (exclusive) and\nI will guess it. After each guess, I will ask you if it is less than\nor equal to some number, and you will respond with \"yes\" or \"no\".\n`, lower, upper)\n    answer := sort.Search(upper-lower, func (i int) bool {\n        fmt.Printf(\"Is your number less than or equal to %d? \", lower+i)\n        s := \"\"\n        fmt.Scanf(\"%s\", &s)\n        return s != \"\" && s[0] == 'y'\n    })\n    fmt.Printf(\"Your number is %d.\\n\", lower+answer)\n}\n", "C": "#include <stdio.h>\n\nint main(){\n  int bounds[ 2 ] = {1, 100};\n  char input[ 2 ] = \"  \";\n    \n  int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n    \n\n  printf( \"Choose a number between %d and %d.\\n\", bounds[ 0 ], bounds[ 1 ] );\n\n  do{\n    switch( input[ 0 ] ){\n      case 'H':\n        bounds[ 1 ] = choice;\n        break;\n      case 'L':\n        bounds[ 0 ] = choice;\n        break;\n      case 'Y':\n        printf( \"\\nAwwwright\\n\" );\n        return 0;\n    }\n    choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;\n\n    printf( \"Is the number %d? (Y/H/L) \", choice );\n  }while( scanf( \"%1s\", input ) == 1 );\n\n  return 0;\n}\n"}
{"id": 45624, "name": "Hash from two arrays", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    keys := []string{\"a\", \"b\", \"c\"}\n    vals := []int{1, 2, 3}\n    hash := map[string]int{}\n    for i, key := range keys {\n        hash[key] = vals[i]\n    }\n    fmt.Println(hash)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define KeyType const char *\n#define ValType int\n\n#define HASH_SIZE 4096\n\n\nunsigned strhashkey( const char * key, int max)\n{\n    unsigned h=0;\n    unsigned hl, hr;\n\n    while(*key) {\n        h += *key;\n        hl= 0x5C5 ^ (h&0xfff00000 )>>18;\n        hr =(h&0x000fffff );\n        h = hl ^ hr ^ *key++;\n    }\n    return h % max;\n}\n\ntypedef struct sHme {\n    KeyType    key;\n    ValType    value;\n    struct sHme  *link;\n} *MapEntry;\n\ntypedef struct he {\n    MapEntry  first, last;\n} HashElement;\n\nHashElement hash[HASH_SIZE];\n    \ntypedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);\ntypedef void (*ValCopyF)(ValType *vdest, ValType vsrc);\ntypedef unsigned (*KeyHashF)( KeyType key, int upperBound );\ntypedef int (*KeyCmprF)(KeyType key1, KeyType key2);\n\nvoid HashAddH( KeyType key, ValType value,\n        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        (*copyVal)(&m_ent->value, value);\n    }\n    else {\n        MapEntry last;\n        MapEntry hme = malloc(sizeof(struct sHme));\n        (*copyKey)(&hme->key, key);\n        (*copyVal)(&hme->value, value);\n        hme->link = NULL;\n        last = hash[hix].last;\n        if (last) {\n\n            last->link = hme;\n        }\n        else\n            hash[hix].first = hme;\n        hash[hix].last = hme;\n    }\n}\n\nint HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )\n{\n    unsigned hix = (*hashKey)(key, HASH_SIZE);\n    MapEntry m_ent;\n    for (m_ent= hash[hix].first;\n            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);\n    if (m_ent) {\n        *val = m_ent->value;\n    }\n    return (m_ent != NULL);\n}\n\nvoid copyStr(const char**dest, const char *src)\n{\n    *dest = strdup(src);\n}\nvoid copyInt( int *dest, int src)\n{\n    *dest = src;\n}\nint strCompare( const char *key1, const char *key2)\n{\n    return strcmp(key1, key2) == 0;\n}\n    \nvoid HashAdd( KeyType key, ValType value )\n{\n    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);\n}\n\nint HashGet(ValType *val, KeyType key)\n{\n    return HashGetH( val, key, &strhashkey, &strCompare);\n}\n\nint main() \n{\n    static const char * keyList[] = {\"red\",\"orange\",\"yellow\",\"green\", \"blue\", \"violet\" };\n    static int valuList[] = {1,43,640, 747, 42, 42};\n    int ix;\n\n    for (ix=0; ix<6; ix++) {\n        HashAdd(keyList[ix], valuList[ix]);\n    }\n    return 0;\n}\n"}
{"id": 45625, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45626, "name": "Bin given limits", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n    n := len(limits)\n    bins := make([]int, n+1)\n    for _, d := range data {\n        index := sort.SearchInts(limits, d) \n        if index < len(limits) && d == limits[index] {\n            index++\n        }\n        bins[index]++\n    }\n    return bins\n}\n\nfunc printBins(limits, bins []int) {\n    n := len(limits)\n    fmt.Printf(\"           < %3d = %2d\\n\", limits[0], bins[0])\n    for i := 1; i < n; i++ {\n        fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n    }\n    fmt.Printf(\">= %3d           = %2d\\n\", limits[n-1], bins[n])\n    fmt.Println()\n}\n\nfunc main() {\n    limitsList := [][]int{\n        {23, 37, 43, 53, 67, 83},\n        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n    }\n\n    dataList := [][]int{\n        {\n            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n        },\n        {\n            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,\n            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,\n            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,\n            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,\n            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,\n            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,\n        },\n    }\n\n    for i := 0; i < len(limitsList); i++ {\n        fmt.Println(\"Example\", i+1, \"\\b\\n\")\n        bins := getBins(limitsList[i], dataList[i])\n        printBins(limitsList[i], bins)\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nsize_t upper_bound(const int* array, size_t n, int value) {\n    size_t start = 0;\n    while (n > 0) {\n        size_t step = n / 2;\n        size_t index = start + step;\n        if (value >= array[index]) {\n            start = index + 1;\n            n -= step + 1;\n        } else {\n            n = step;\n        }\n    }\n    return start;\n}\n\nint* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {\n    int* result = calloc(nlimits + 1, sizeof(int));\n    if (result == NULL)\n        return NULL;\n    for (size_t i = 0; i < ndata; ++i)\n        ++result[upper_bound(limits, nlimits, data[i])];\n    return result;\n}\n\nvoid print_bins(const int* limits, size_t n, const int* bins) {\n    if (n == 0)\n        return;\n    printf(\"           < %3d: %2d\\n\", limits[0], bins[0]);\n    for (size_t i = 1; i < n; ++i)\n        printf(\">= %3d and < %3d: %2d\\n\", limits[i - 1], limits[i], bins[i]);\n    printf(\">= %3d          : %2d\\n\", limits[n - 1], bins[n]);\n}\n\nint main() {\n    const int limits1[] = {23, 37, 43, 53, 67, 83};\n    const int data1[] = {95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57,\n                         5,  53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,\n                         8,  9,  32, 84, 7,  87, 46, 19, 30, 37, 96, 6,  98,\n                         40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n    printf(\"Example 1:\\n\");\n    size_t n = sizeof(limits1) / sizeof(int);\n    int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits1, n, b);\n    free(b);\n\n    const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};\n    const int data2[] = {\n        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,\n        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,\n        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,\n        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,\n        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,\n        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,\n        101, 684, 727, 749};\n\n    printf(\"\\nExample 2:\\n\");\n    n = sizeof(limits2) / sizeof(int);\n    b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));\n    if (b == NULL) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return EXIT_FAILURE;\n    }\n    print_bins(limits2, n, b);\n    free(b);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45627, "name": "Fractal tree", "Go": "package main\n\n\n\n\n\n\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width/2, height*9/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi/180)\n    y2 := y - distance*math.Cos(direction*math.Pi/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n", "C": "#include <SDL/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \n#define SCALE          5     \n#define BRANCHES       14    \n#define ROTATION_SCALE 0.75  \n#define INITIAL_LENGTH 50    \n \ndouble rand_fl(){\n  return (double)rand() / (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w / 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI / 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n"}
{"id": 45628, "name": "Colour pinstripe_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar palette = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc pinstripe(dc *gg.Context) {\n    w := dc.Width()\n    h := dc.Height() / 4\n    for b := 1; b <= 4; b++ {\n        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {\n            dc.SetHexColor(palette[ci%8])\n            y := h * (b - 1)\n            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))\n            dc.Fill()\n        }\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(900, 600)\n    pinstripe(dc)\n    dc.SavePNG(\"color_pinstripe.png\")\n}\n", "C": "#include<graphics.h>\n#include<conio.h>\n\n#define sections 4\n\nint main()\n{\n\tint d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;\n\tinitgraph(&d,&m,\"c:/turboc3/bgi\");\n\t\n\tmaxX = getmaxx();\n\tmaxY = getmaxy();\n\t\n\tfor(y=0;y<maxY;y+=maxY/sections)\n\t{\n\t\tfor(x=0;x<maxX;x+=increment)\n\t\t{\n\t\t\tsetfillstyle(SOLID_FILL,(colour++)%16);\n\t\t\tbar(x,y,x+increment,y+maxY/sections);\n\t\t}\n\t\tincrement++;\n\t\tcolour = 0;\n\t}\n\t\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n"}
{"id": 45629, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 45630, "name": "Doomsday rule", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n    dates := []string{\n        \"1800-01-06\",\n        \"1875-03-29\",\n        \"1915-12-07\",\n        \"1970-12-23\",\n        \"2043-05-14\",\n        \"2077-02-12\",\n        \"2101-04-02\",\n    }\n\n    fmt.Println(\"Days of week given by Doomsday rule:\")\n    for _, date := range dates {\n        y, _ := strconv.Atoi(date[0:4])\n        m, _ := strconv.Atoi(date[5:7])\n        m--\n        d, _ := strconv.Atoi(date[8:10])\n        a := anchorDay(y)\n        f := firstDaysCommon[m]\n        if isLeapYear(y) {\n            f = firstDaysLeap[m]\n        }\n        w := d - f\n        if w < 0 {\n            w = 7 + w\n        }\n        dow := (a + w) % 7\n        fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdint.h>\n#include <stdbool.h>\n\ntypedef struct { \n    uint16_t year;\n    uint8_t month;\n    uint8_t day;\n} Date;\n\nbool leap(uint16_t year) {\n    return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst char *weekday(Date date) {\n    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n    static const char *days[] = {\n        \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n        \"Thursday\", \"Friday\", \"Saturday\"\n    };\n    \n    unsigned c = date.year/100, r = date.year%100;\n    unsigned s = r/12, t = r%12;\n    \n    unsigned c_anchor = (5 * (c%4) + 2) % 7;\n    unsigned doom = (s + t + (t/4) + c_anchor) % 7;\n    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n    return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n    const char *past = \"was\", *future = \"will be\";\n    const char *months[] = { \"\",\n        \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n        \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n    };\n    \n    const Date dates[] = {\n        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n        {2077,2,12}, {2101,4,2}\n    };\n    \n    int i;\n    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {\n        printf(\"%s %d, %d %s on a %s.\\n\",\n            months[dates[i].month], dates[i].day, dates[i].year,\n            dates[i].year > 2021 ? future : past,\n            weekday(dates[i]));\n    }\n    \n    return 0;\n}\n"}
{"id": 45631, "name": "Sorting algorithms_Cocktail sort with shifting bounds", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc cocktailShakerSort(a []int) {\n    var begin = 0\n    var end = len(a) - 2\n    for begin <= end {\n        newBegin := end\n        newEnd := begin\n        for i := begin; i <= end; i++ {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newEnd = i\n            }\n        }\n        end = newEnd - 1\n        for i := end; i >= begin; i-- {\n            if a[i] > a[i+1] {\n                a[i+1], a[i] = a[i], a[i+1]\n                newBegin = i\n            }\n        }\n        begin = newBegin + 1\n    }\n}\n\n\nfunc cocktailSort(a []int) {\n    last := len(a) - 1\n    for {\n        swapped := false\n        for i := 0; i < last; i++ {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n        swapped = false\n        for i := last - 1; i >= 0; i-- {\n            if a[i] > a[i+1] {\n                a[i], a[i+1] = a[i+1], a[i]\n                swapped = true\n            }\n        }\n        if !swapped {\n            return\n        }\n    }\n}\n\nfunc main() {\n    \n    a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}\n    fmt.Println(\"Original array:\", a)\n    b := make([]int, len(a))\n    copy(b, a) \n    cocktailSort(a)\n    fmt.Println(\"Cocktail sort :\", a)\n    cocktailShakerSort(b)\n    fmt.Println(\"C/Shaker sort :\", b)\n\n    \n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"\\nRelative speed of the two sorts\")\n    fmt.Println(\"  N    x faster (CSS v CS)\")\n    fmt.Println(\"-----  -------------------\")\n    const runs = 10 \n    for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {\n        sum := 0.0\n        for i := 1; i <= runs; i++ {\n            \n            \n            nums := make([]int, n)\n            for i := 0; i < n; i++ {\n                rn := rand.Intn(100000)\n                if i%2 == 1 {\n                    rn = -rn\n                }\n                nums[i] = rn\n            }\n            \n            nums2 := make([]int, n)\n            copy(nums2, nums)\n\n            start := time.Now()\n            cocktailSort(nums)\n            elapsed := time.Since(start)\n            start2 := time.Now()\n            cocktailShakerSort(nums2)\n            elapsed2 := time.Since(start2)\n            sum += float64(elapsed) / float64(elapsed2)\n        }\n        fmt.Printf(\" %2dk      %0.3f\\n\", n/1000, sum/runs)\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char* p1, char* p2, size_t size) {\n    for (; size-- > 0; ++p1, ++p2) {\n        char tmp = *p1;\n        *p1 = *p2;\n        *p2 = tmp;\n    }\n}\n\nvoid cocktail_shaker_sort(void* base, size_t count, size_t size,\n                          int (*cmp)(const void*, const void*)) {\n    char* begin = base;\n    char* end = base + size * count;\n    if (end == begin)\n        return;\n    for (end -= size; begin < end; ) {\n        char* new_begin = end;\n        char* new_end = begin;\n        for (char* p = begin; p < end; p += size) {\n            char* q = p + size;\n            if (cmp(p, q) > 0) {\n                swap(p, q, size);\n                new_end = p;\n            }\n        }\n        end = new_end;\n        for (char* p = end; p > begin; p -= size) {\n            char* q = p - size;\n            if (cmp(q, p) > 0) {\n                swap(p, q, size);\n                new_begin = p;\n            }\n        }\n        begin = new_begin;\n    }\n}\n\nint string_compare(const void* p1, const void* p2) {\n    const char* const* s1 = p1;\n    const char* const* s2 = p2;\n    return strcmp(*s1, *s2);\n}\n\nvoid print(const char** a, size_t len) {\n    for (size_t i = 0; i < len; ++i)\n        printf(\"%s \", a[i]);\n    printf(\"\\n\");\n}\n\nint main() {\n    const char* a[] = { \"one\", \"two\", \"three\", \"four\", \"five\",\n        \"six\", \"seven\", \"eight\" };\n    const size_t len = sizeof(a)/sizeof(a[0]);\n    printf(\"before: \");\n    print(a, len);\n    cocktail_shaker_sort(a, len, sizeof(char*), string_compare);\n    printf(\"after: \");\n    print(a, len);\n    return 0;\n}\n"}
{"id": 45632, "name": "Animate a pendulum", "Go": "package main\n\nimport (\n\t\"github.com/google/gxui\"\n\t\"github.com/google/gxui/drivers/gl\"\n\t\"github.com/google/gxui/math\"\n\t\"github.com/google/gxui/themes/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\n\n\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 / 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n", "C": "#include <stdlib.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <sys/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret / 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl / 2) * us;\n\tomega += accl * us;\n\n\t\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);\n\t\tomega = 0;\n\t}\n\taccl = -g / length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) / 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g / length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n"}
{"id": 45633, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 45634, "name": "Gray code", "Go": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n    return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n    for ; g != 0; g >>= 1 {\n        b ^= g\n    }\n    return\n}\n\nfunc main() {\n    fmt.Println(\"decimal  binary   gray    decoded\")\n    for b := 0; b < 32; b++ {\n        g := enc(b)\n        d := dec(g)\n        fmt.Printf(\"  %2d     %05b   %05b   %05b  %2d\\n\", b, b, g, d, d)\n    }\n}\n", "C": "int gray_encode(int n) {\n    return n ^ (n >> 1);\n}\n\nint gray_decode(int n) {\n    int p = n;\n    while (n >>= 1) p ^= n;\n    return p;\n}\n"}
{"id": 45635, "name": "Create a file on magnetic tape", "Go": "package main\n\nimport (\n        \"archive/tar\"\n        \"compress/gzip\"\n        \"flag\"\n        \"io\"\n        \"log\"\n        \"os\"\n        \"time\"\n)\n\nfunc main() {\n        filename := flag.String(\"file\", \"TAPE.FILE\", \"filename within TAR\")\n        data := flag.String(\"data\", \"\", \"data for file\")\n        outfile := flag.String(\"out\", \"\", \"output file or device (e.g. /dev/tape)\")\n        gzipFlag := flag.Bool(\"gzip\", false, \"use gzip compression\")\n        flag.Parse()\n\n        var w io.Writer = os.Stdout\n        if *outfile != \"\" {\n                f, err := os.Create(*outfile)\n                if err != nil {\n                        log.Fatalf(\"opening/creating %q: %v\", *outfile, err)\n                }\n                defer f.Close()\n                w = f\n        }\n\n        if *gzipFlag {\n                zw := gzip.NewWriter(w)\n                defer zw.Close()\n                w = zw\n        }\n\n        tw := tar.NewWriter(w)\n        defer tw.Close()\n        w = tw\n        tw.WriteHeader(&tar.Header{\n                Name:     *filename,\n                Mode:     0660,\n                Size:     int64(len(*data)),\n                ModTime:  time.Now(),\n                Typeflag: tar.TypeReg,\n                Uname:    \"guest\",\n                Gname:    \"guest\",\n        })\n\n        _, err := w.Write([]byte(*data))\n        if err != nil {\n                log.Fatal(\"writing data:\", err)\n        }\n}\n", "C": "#include<stdio.h>\n\nint main()\n{\n\tFILE* fp = fopen(\"TAPE.FILE\",\"w\");\n\t\n\tfprintf(fp,\"This code should be able to write a file to magnetic tape.\\n\");\n\tfprintf(fp,\"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\\n\");\n\tfprintf(fp,\"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"If you happen to have one, please try to compile and execute me on that system.\\n\");\n\tfprintf(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\");\n\tfprintf(fp,\"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\\n\");\n\tfprintf(fp,\"EOF\");\n\t\n\tfclose(fp);\n\t\n\treturn 0;\n}\n"}
{"id": 45636, "name": "Sorting algorithms_Heapsort", "Go": "package main\n\nimport (\n  \"sort\"\n  \"container/heap\"\n  \"fmt\"\n)\n\ntype HeapHelper struct {\n    container sort.Interface\n    length    int\n}\n\nfunc (self HeapHelper) Len() int { return self.length }\n\nfunc (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }\nfunc (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }\n\nfunc (self *HeapHelper) Push(x interface{}) { panic(\"impossible\") }\nfunc (self *HeapHelper) Pop() interface{} {\n    self.length--\n    return nil \n}\n\nfunc heapSort(a sort.Interface) {\n    helper := HeapHelper{ a, a.Len() }\n    heap.Init(&helper)\n    for helper.length > 0 {\n        heap.Pop(&helper)\n    }\n}\n\nfunc main() {\n    a := []int{170, 45, 75, -90, -802, 24, 2, 66}\n    fmt.Println(\"before:\", a)\n    heapSort(sort.IntSlice(a))\n    fmt.Println(\"after: \", a)\n}\n", "C": "#include <stdio.h>\n\nint max (int *a, int n, int i, int j, int k) {\n    int m = i;\n    if (j < n && a[j] > a[m]) {\n        m = j;\n    }\n    if (k < n && a[k] > a[m]) {\n        m = k;\n    }\n    return m;\n}\n\nvoid downheap (int *a, int n, int i) {\n    while (1) {\n        int j = max(a, n, i, 2 * i + 1, 2 * i + 2);\n        if (j == i) {\n            break;\n        }\n        int t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n        i = j;\n    }\n}\n\nvoid heapsort (int *a, int n) {\n    int i;\n    for (i = (n - 2) / 2; i >= 0; i--) {\n        downheap(a, n, i);\n    }\n    for (i = 0; i < n; i++) {\n        int t = a[n - i - 1];\n        a[n - i - 1] = a[0];\n        a[0] = t;\n        downheap(a, n - i - 1, 0);\n    }\n}\n\nint main () {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    heapsort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 45637, "name": "Playing cards", "Go": "package cards\n\nimport (\n\t\"math/rand\"\n)\n\n\ntype Suit uint8\n\n\nconst (\n\tSpade   Suit = 3\n\tHeart   Suit = 2\n\tDiamond Suit = 1\n\tClub    Suit = 0\n)\n\nfunc (s Suit) String() string {\n\tconst suites = \"CDHS\" \n\treturn suites[s : s+1]\n}\n\n\ntype Rank uint8\n\n\nconst (\n\tAce   Rank = 1\n\tTwo   Rank = 2\n\tThree Rank = 3\n\tFour  Rank = 4\n\tFive  Rank = 5\n\tSix   Rank = 6\n\tSeven Rank = 7\n\tEight Rank = 8\n\tNine  Rank = 9\n\tTen   Rank = 10\n\tJack  Rank = 11\n\tQueen Rank = 12\n\tKing  Rank = 13\n)\n\nfunc (r Rank) String() string {\n\tconst ranks = \"A23456789TJQK\"\n\treturn ranks[r-1 : r]\n}\n\n\n\n\ntype Card uint8\n\n\nfunc NewCard(r Rank, s Suit) Card {\n\treturn Card(13*uint8(s) + uint8(r-1))\n}\n\n\nfunc (c Card) RankSuit() (Rank, Suit) {\n\treturn Rank(c%13 + 1), Suit(c / 13)\n}\n\n\nfunc (c Card) Rank() Rank {\n\treturn Rank(c%13 + 1)\n}\n\n\nfunc (c Card) Suit() Suit {\n\treturn Suit(c / 13)\n}\n\nfunc (c Card) String() string {\n\treturn c.Rank().String() + c.Suit().String()\n}\n\n\ntype Deck []Card\n\n\nfunc NewDeck() Deck {\n\td := make(Deck, 52)\n\tfor i := range d {\n\t\td[i] = Card(i)\n\t}\n\treturn d\n}\n\n\n\nfunc (d Deck) String() string {\n\ts := \"\"\n\tfor i, c := range d {\n\t\tswitch {\n\t\tcase i == 0: \n\t\tcase i%13 == 0:\n\t\t\ts += \"\\n\"\n\t\tdefault:\n\t\t\ts += \" \"\n\t\t}\n\t\ts += c.String()\n\t}\n\treturn s\n}\n\n\nfunc (d Deck) Shuffle() {\n\tfor i := range d {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}\n\n\nfunc (d Deck) Contains(tc Card) bool {\n\tfor _, c := range d {\n\t\tif c == tc {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (d *Deck) AddDeck(decks ...Deck) {\n\tfor _, o := range decks {\n\t\t*d = append(*d, o...)\n\t}\n}\n\n\nfunc (d *Deck) AddCard(c Card) {\n\t*d = append(*d, c)\n}\n\n\n\nfunc (d *Deck) Draw(n int) Deck {\n\told := *d\n\t*d = old[n:]\n\treturn old[:n:n]\n}\n\n\n\n\nfunc (d *Deck) DrawCard() (Card, bool) {\n\tif len(*d) == 0 {\n\t\treturn 0, false\n\t}\n\told := *d\n\t*d = old[1:]\n\treturn old[0], true\n}\n\n\n\n\n\n\n\n\nfunc (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {\n\tfor i := 0; i < cards; i++ {\n\t\tfor j := range hands {\n\t\t\tif len(*d) == 0 {\n\t\t\t\treturn hands, false\n\t\t\t}\n\t\t\thands[j] = append(hands[j], (*d)[0])\n\t\t\t*d = (*d)[1:]\n\t\t}\n\t}\n\treturn hands, true\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint locale_ok = 0;\n\nwchar_t s_suits[] = L\"♠♥♦♣\";\n\n\n\nconst char *s_suits_ascii[] = { \"S\", \"H\", \"D\", \"C\" };\nconst char *s_nums[] = { \"WHAT\",\n\t\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\",\n\t\"OVERFLOW\"\n};\n\ntypedef struct { int suit, number, _s; } card_t, *card;\ntypedef struct { int n; card_t cards[52]; } deck_t, *deck;\n\nvoid show_card(card c)\n{\n\tif (locale_ok)\n\t\tprintf(\" %lc%s\", s_suits[c->suit], s_nums[c->number]);\n\telse\n\t\tprintf(\" %s%s\", s_suits_ascii[c->suit], s_nums[c->number]);\n}\n\ndeck new_deck()\n{\n\tint i, j, k;\n\tdeck d = malloc(sizeof(deck_t));\n\td->n = 52;\n\tfor (i = k = 0; i < 4; i++)\n\t\tfor (j = 1; j <= 13; j++, k++) {\n\t\t\td->cards[k].suit = i;\n\t\t\td->cards[k].number = j;\n\t\t}\n\treturn d;\n}\n\nvoid show_deck(deck d)\n{\n\tint i;\n\tprintf(\"%d cards:\", d->n);\n\tfor (i = 0; i < d->n; i++)\n\t\tshow_card(d->cards + i);\n\tprintf(\"\\n\");\n}\n\nint cmp_card(const void *a, const void *b)\n{\n\tint x = ((card)a)->_s, y = ((card)b)->_s;\n\treturn x < y ? -1 : x > y;\n}\n\ncard deal_card(deck d)\n{\n\tif (!d->n) return 0;\n\treturn d->cards + --d->n;\n}\n\nvoid shuffle_deck(deck d)\n{\n\tint i;\n\tfor (i = 0; i < d->n; i++)\n\t\td->cards[i]._s = rand();\n\tqsort(d->cards, d->n, sizeof(card_t), cmp_card);\n}\n\nint main()\n{\n\tint i, j;\n\tdeck d = new_deck();\n\n\tlocale_ok = (0 != setlocale(LC_CTYPE, \"\"));\n\n\tprintf(\"New deck, \"); show_deck(d);\n\n\tprintf(\"\\nShuffle and deal to three players:\\n\");\n\tshuffle_deck(d);\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 5; j++)\n\t\t\tshow_card(deal_card(d));\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"Left in deck \"); show_deck(d);\n\n\t\n\t\n\treturn 0;\n}\n"}
{"id": 45638, "name": "Arrays", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \n    \n    \n    var a [5]int\n\n    \n    \n    fmt.Println(\"len(a) =\", len(a))\n\n    \n    fmt.Println(\"a =\", a)\n\n    \n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \n    fmt.Println(\"a[0] =\", a[0])\n\n    \n    s := a[:4] \n    fmt.Println(\"s =\", s)\n\n    \n    \n    \n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \n    \n}\n", "C": " char foo()\n{\nchar array[5] = {3,6,9,12,15};\nreturn array[2];\n}\n"}
{"id": 45639, "name": "Sierpinski carpet", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \n        \n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim / 3; d; d /= 3)\n\t\t\t\tif ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 45640, "name": "Sorting algorithms_Bogosort", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"unsorted:\", list)\n    temp := make([]int, len(list))\n    copy(temp, list)\n    for !sort.IntsAreSorted(temp) {\n        for i, v := range rand.Perm(len(list)) {\n            temp[i] = list[v]\n        }\n    }\n    fmt.Println(\"sorted!  \", temp)\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nbool is_sorted(int *a, int n)\n{\n  while ( --n >= 1 ) {\n    if ( a[n] < a[n-1] ) return false;\n  }\n  return true;\n}\n\nvoid shuffle(int *a, int n)\n{\n  int i, t, r;\n  for(i=0; i < n; i++) {\n    t = a[i];\n    r = rand() % n;\n    a[i] = a[r];\n    a[r] = t;\n  }\n}\n\nvoid bogosort(int *a, int n)\n{\n  while ( !is_sorted(a, n) ) shuffle(a, n);\n}\n\nint main()\n{\n  int numbers[] = { 1, 10, 9,  7, 3, 0 };\n  int i;\n\n  bogosort(numbers, 6);\n  for (i=0; i < 6; i++) printf(\"%d \", numbers[i]);\n  printf(\"\\n\");\n}\n"}
{"id": 45641, "name": "Merge and aggregate datasets", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\nvar patientDir = make(map[int]string)\n\n\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() / float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       | %-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \n    visitNew(1001, \"\", 6.6)          \n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n", "C": "\n#include <ctime>\n#include <cstdint>\nextern \"C\" {\n  int64_t from date(const char* string) {\n    struct tm tmInfo = {0};\n    strptime(string, \"%Y-%m-%d\", &tmInfo);\n    return mktime(&tmInfo); \n  }\n}\n"}
{"id": 45642, "name": "Euler method", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\ntype fdy func(float64, float64) float64\n\n\n\n\nfunc eulerStep(f fdy, x, y, h float64) float64 {\n    return y + h*f(x, y)\n}\n\n\n\n\n\n\nfunc newCoolingRate(k float64) func(float64) float64 {\n    return func(deltaTemp float64) float64 {\n        return -k * deltaTemp\n    }\n}\n\n\n\nfunc newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n    return func(time float64) float64 {\n        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n    }\n}\n\n\n\n\n\n\nfunc newCoolingRateDy(k, ambientTemp float64) fdy {\n    crf := newCoolingRate(k)\n    \n    \n    \n    return func(_, objectTemp float64) float64 {\n        return crf(objectTemp - ambientTemp)\n    }\n}\n\nfunc main() {\n    k := .07\n    tempRoom := 20.\n    tempObject := 100.\n    fcr := newCoolingRateDy(k, tempRoom)\n    analytic := newTempFunc(k, tempRoom, tempObject)\n    for _, deltaTime := range []float64{2, 5, 10} {\n        fmt.Printf(\"Step size = %.1f\\n\", deltaTime)\n        fmt.Println(\" Time Euler's Analytic\")\n        temp := tempObject\n        for time := 0.; time <= 100; time += deltaTime {\n            fmt.Printf(\"%5.1f %7.3f %7.3f\\n\", time, temp, analytic(time))\n            temp = eulerStep(fcr, time, temp, deltaTime)\n        }\n        fmt.Println()\n    }\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\ntypedef double (*deriv_f)(double, double);\n#define FMT \" %7.3f\"\n\nvoid ivp_euler(deriv_f f, double y, int step, int end_t)\n{\n\tint t = 0;\n\n\tprintf(\" Step %2d: \", (int)step);\n\tdo {\n\t\tif (t % 10 == 0) printf(FMT, y);\n\t\ty += step * f(t, y);\n\t} while ((t += step) <= end_t);\n\tprintf(\"\\n\");\n}\n\nvoid analytic()\n{\n\tdouble t;\n\tprintf(\"    Time: \");\n\tfor (t = 0; t <= 100; t += 10) printf(\" %7g\", t);\n\tprintf(\"\\nAnalytic: \");\n\n\tfor (t = 0; t <= 100; t += 10)\n\t\tprintf(FMT, 20 + 80 * exp(-0.07 * t));\n\tprintf(\"\\n\");\n}\n\ndouble cooling(double t, double temp)\n{\n\treturn -0.07 * (temp - 20);\n}\n\nint main()\n{\n\tanalytic();\n\tivp_euler(cooling, 100, 2, 100);\n\tivp_euler(cooling, 100, 5, 100);\n\tivp_euler(cooling, 100, 10, 100);\n\n\treturn 0;\n}\n"}
{"id": 45643, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 45644, "name": "Sequence of non-squares", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc remarkable(n int) int {\n    return n + int(.5+math.Sqrt(float64(n)))\n}\n\nfunc main() {\n    \n    fmt.Println(\"  n  r(n)\")\n    fmt.Println(\"---  ---\")\n    for n := 1; n <= 22; n++ {\n        fmt.Printf(\"%3d  %3d\\n\", n, remarkable(n))\n    }\n\n    \n    const limit = 1e6\n    fmt.Println(\"\\nChecking for squares for n <\", limit)\n    next := 2\n    nextSq := 4\n    for n := 1; n < limit; n++ {\n        r := remarkable(n)\n        switch {\n        case r == nextSq:\n            panic(n)\n        case r > nextSq:\n            fmt.Println(nextSq, \"didn't occur\")\n            next++\n            nextSq = next * next\n        }\n    }\n    fmt.Println(\"No squares occur for n <\", limit)\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <assert.h>\n\nint nonsqr(int n) {\n    return n + (int)(0.5 + sqrt(n));\n    \n}\n\nint main() {\n    int i;\n    \n    \n    for (i = 1; i < 23; i++)\n        printf(\"%d \", nonsqr(i));\n    printf(\"\\n\");\n    \n    \n    for (i = 1; i < 1000000; i++) {\n        double j = sqrt(nonsqr(i));\n        assert(j != floor(j));\n    }\n    return 0;\n}\n"}
{"id": 45645, "name": "Substring", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n", "C": "\n#define _CRT_SECURE_NO_WARNINGS \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45646, "name": "JortSort", "Go": "package main\n\nimport (\n  \"log\"\n  \"sort\"\n)\n\nfunc main() {\n  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) \n  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       \n  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    \n  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       \n}\n\nfunc jortSort(a []int) bool {\n  c := make([]int, len(a))\n  copy(c, a)\n  sort.Ints(a)\n  for k, v := range c {\n    if v == a[k] {\n      continue\n    } else {\n      return false\n    }\n  }\n  return true\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint number_of_digits(int x){\n    int NumberOfDigits;\n    for(NumberOfDigits=0;x!=0;NumberOfDigits++){\n        x=x/10;\n    }\n    return NumberOfDigits;\n}\n\nint* convert_array(char array[], int NumberOfElements)  \n{\n    int *convertedArray=malloc(NumberOfElements*sizeof(int));\n    int originalElement, convertedElement;\n\n    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)\n    {\n       convertedArray[convertedElement]=atoi(&array[originalElement]);\n       originalElement+=number_of_digits(convertedArray[convertedElement])+1; \n\n    }\n    return convertedArray;\n}\n\n\n\nint isSorted(int array[], int numberOfElements){\n    int sorted=1;\n    for(int counter=0;counter<numberOfElements;counter++){\n        if(counter!=0 && array[counter-1]>array[counter]) sorted--;\n\n    }\n    return sorted;\n}\nint main(int argc, char* argv[])\n{\n    int* convertedArray;\n\n\n    convertedArray=convert_array(*(argv+1), argc-1);\n\n\n\n    if(isSorted(convertedArray, argc-1)==1) printf(\"Did you forgot to turn on your brain?! This array is already sorted!\\n\");\n    else if(argc-1<=10) printf(\"Am I really supposed to sort this? Sort it by yourself!\\n\");\n    else printf(\"Am I really supposed to sort this? Bhahahaha!\\n\");\n    free(convertedArray);\n    return 0;\n\n\n\n}\n"}
{"id": 45647, "name": "Leap year", "Go": "func isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n", "C": "#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case / sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n"}
{"id": 45648, "name": "Combinations and permutations", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tvar n, p int64\n\tfmt.Printf(\"A sample of permutations from 1 to 12:\\n\")\n\tfor n = 1; n < 13; n++ {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 10 to 60:\\n\")\n\tfor n = 10; n < 61; n += 10 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of permutations from 5 to 15000:\\n\")\n\tnArr := [...]int64{5, 50, 500, 1000, 5000, 15000}\n\tfor _, n = range nArr {\n\t\tp = n / 3\n\t\tfmt.Printf(\"P(%d,%d) = %d\\n\", n, p, perm(big.NewInt(n), big.NewInt(p)))\n\t}\n\tfmt.Printf(\"\\nA sample of combinations from 100 to 1000:\\n\")\n\tfor n = 100; n < 1001; n += 100 {\n\t\tp = n / 3\n\t\tfmt.Printf(\"C(%d,%d) = %d\\n\", n, p, comb(big.NewInt(n), big.NewInt(p)))\n\t}\n}\n\nfunc fact(n *big.Int) *big.Int {\n\tif n.Sign() < 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tr := big.NewInt(1)\n\ti := big.NewInt(2)\n\tfor i.Cmp(n) < 1 {\n\t\tr.Mul(r, i)\n\t\ti.Add(i, big.NewInt(1))\n\t}\n\treturn r\n}\n\nfunc perm(n, k *big.Int) *big.Int {\n\tr := fact(n)\n\tr.Div(r, fact(n.Sub(n, k)))\n\treturn r\n}\n\nfunc comb(n, r *big.Int) *big.Int {\n\tif r.Cmp(n) == 1 {\n\t\treturn big.NewInt(0)\n\t}\n\tif r.Cmp(n) == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\tc := fact(n)\n\tden := fact(n.Sub(n, r))\n\tden.Mul(den, fact(r))\n\tc.Div(c, den)\n\treturn c\n}\n", "C": "#include <gmp.h>\n\nvoid perm(mpz_t out, int n, int k)\n{\n\tmpz_set_ui(out, 1);\n\tk = n - k;\n\twhile (n > k) mpz_mul_ui(out, out, n--);\n}\n\nvoid comb(mpz_t out, int n, int k)\n{\n\tperm(out, n, k);\n\twhile (k) mpz_divexact_ui(out, out, k--);\n}\n\nint main(void)\n{\n\tmpz_t x;\n\tmpz_init(x);\n\n\tperm(x, 1000, 969);\n\tgmp_printf(\"P(1000,969) = %Zd\\n\", x);\n\n\tcomb(x, 1000, 969);\n\tgmp_printf(\"C(1000,969) = %Zd\\n\", x);\n\treturn 0;\n}\n"}
{"id": 45649, "name": "Sort numbers lexicographically", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc lexOrder(n int) []int {\n    first, last, k := 1, n, n\n    if n < 1 {\n        first, last, k = n, 1, 2-n\n    }\n    strs := make([]string, k)\n    for i := first; i <= last; i++ {\n        strs[i-first] = strconv.Itoa(i)\n    }\n    sort.Strings(strs)\n    ints := make([]int, k)\n    for i := 0; i < k; i++ {\n        ints[i], _ = strconv.Atoi(strs[i])\n    }\n    return ints\n}\n\nfunc main() {\n    fmt.Println(\"In lexicographical order:\\n\")\n    for _, n := range []int{0, 5, 13, 21, -22} {\n        fmt.Printf(\"%3d: %v\\n\", n, lexOrder(n))\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint compareStrings(const void *a, const void *b) {\n    const char **aa = (const char **)a;\n    const char **bb = (const char **)b;\n    return strcmp(*aa, *bb);\n}\n\nvoid lexOrder(int n, int *ints) {\n    char **strs;\n    int i, first = 1, last = n, k = n, len;\n    if (n < 1) {\n        first = n; last = 1; k = 2 - n;\n    } \n    strs = malloc(k * sizeof(char *));\n    for (i = first; i <= last; ++i) {\n        if (i >= 1) len = (int)log10(i) + 2;\n        else if (i == 0) len = 2;\n        else len = (int)log10(-i) + 3; \n        strs[i-first] = malloc(len);\n        sprintf(strs[i-first], \"%d\", i);\n    }\n    qsort(strs, k, sizeof(char *), compareStrings);\n    for (i = 0; i < k; ++i) {\n        ints[i] = atoi(strs[i]);\n        free(strs[i]);\n    }\n    free(strs);\n}\n\nint main() {\n    int i, j, k, n,  *ints;\n    int numbers[5] = {0, 5, 13, 21, -22};\n    printf(\"In lexicographical order:\\n\\n\");\n    for (i = 0; i < 5; ++i) {\n        k = n = numbers[i];\n        if (k < 1) k = 2 - k;\n        ints = malloc(k * sizeof(int));\n        lexOrder(n, ints);\n        printf(\"%3d: [\", n);\n        for (j = 0; j < k; ++j) {\n            printf(\"%d \", ints[j]);\n        }\n        printf(\"\\b]\\n\");\n        free(ints);\n    }\n    return 0;\n}\n"}
{"id": 45650, "name": "Number names", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor _, n := range []int64{12, 1048576, 9e18, -2, 0} {\n\t\tfmt.Println(say(n))\n\t}\n}\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nconst char *ones[] = { 0, \"one\", \"two\", \"three\", \"four\",\n\t\"five\", \"six\", \"seven\", \"eight\", \"nine\", \n\t\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\nconst char *tens[] = { 0, \"ten\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\nconst char *llions[] = { 0, \"thousand\", \"million\", \"billion\", \"trillion\",\n\n\n\t};\nconst int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;\n\nint say_hundred(const char *s, int len, int depth, int has_lead)\n{\n\tint c[3], i;\n\tfor (i = -3; i < 0; i++) {\n\t\tif (len + i >= 0) c[i + 3] = s[len + i] - '0';\n\t\telse c[i + 3] = 0;\n\t}\n\tif (!(c[0] + c[1] + c[2])) return 0;\n\n\tif (c[0]) {\n\t\tprintf(\"%s hundred\", ones[c[0]]);\n\t\thas_lead = 1;\n\t}\n\n\tif (has_lead && (c[1] || c[2]))\n\t\tprintf((!depth || c[0]) && (!c[0] || !c[1]) ? \"and \" :\n\t\t\tc[0] ? \" \" : \"\");\n\n\tif (c[1] < 2) {\n\t\tif (c[1] || c[2]) printf(\"%s\", ones[c[1] * 10 + c[2]]);\n\t} else {\n\t\tif (c[1]) {\n\t\t\tprintf(\"%s\", tens[c[1]]);\n\t\t\tif (c[2]) putchar('-');\n\t\t}\n\t\tif (c[2]) printf(\"%s\", ones[c[2]]);\n\t}\n\n\treturn 1;\n}\n\nint say_maxillion(const char *s, int len, int depth, int has_lead)\n{\n\tint n = len / 3, r = len % 3;\n\tif (!r) {\n\t\tn--;\n\t\tr = 3;\n\t}\n\tconst char *e = s + r;\n\tdo {\n\t\tif (say_hundred(s, r, n, has_lead) && n) {\n\t\t\thas_lead = 1;\n\t\t\tprintf(\" %s\", llions[n]);\n\t\t\tif (!depth) printf(\", \");\n\t\t\telse printf(\" \");\n\t\t}\n\t\ts = e; e += 3;\n\t} while (r = 3, n--);\n\n\treturn 1;\n}\n\nvoid say_number(const char *s)\n{\n\tint len, i, got_sign = 0;\n\n\twhile (*s == ' ') s++;\n\tif (*s < '0' || *s > '9') {\n\t\tif (*s == '-') got_sign = -1;\n\t\telse if (*s == '+') got_sign = 1;\n\t\telse goto nan;\n\t\ts++;\n\t} else\n\t\tgot_sign = 1;\n\n\twhile (*s == '0') {\n\t\ts++;\n\t\tif (*s == '\\0') {\n\t\t\tprintf(\"zero\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlen = strlen(s);\n\tif (!len) goto nan;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (s[i] < '0' || s[i] > '9') {\n\t\t\tprintf(\"(not a number)\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (got_sign == -1) printf(\"minus \");\n\n\tint n = len / maxillion;\n\tint r = len % maxillion;\n\tif (!r) {\n\t\tr = maxillion;\n\t\tn--;\n\t}\n\n\tconst char *end = s + len - n * maxillion;\n\tint has_lead = 0;\n\tdo {\n\t\tif ((has_lead = say_maxillion(s, r, n, has_lead))) {\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\tprintf(\" %s\", llions[maxillion / 3]);\n\t\t\tif (n) printf(\", \");\n\t\t}\n\t\tn--;\n\t\tr = maxillion;\n\t\ts = end;\n\t\tend += r;\n\t} while (n >= 0);\n\n\tprintf(\"\\n\");\n\treturn;\n\nnan:\tprintf(\"not a number\\n\");\n\treturn;\n}\n\nint main()\n{\n\tsay_number(\"-42\");\n\tsay_number(\"1984\");\n\tsay_number(\"10000\");\n\tsay_number(\"1024\");\n\tsay_number(\"1001001001001\");\n\tsay_number(\"123456789012345678901234567890123456789012345678900000001\");\n\treturn 0;\n}\n"}
{"id": 45651, "name": "Compare length of two strings", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n\nfunc compareStrings(strings ...string) {\n\t\n\t\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint cmp(const int* a, const int* b)\n{\n    return *b - *a; \n}\n\nvoid compareAndReportStringsLength(const char* strings[], const int n)\n{\n    if (n > 0)\n    {\n        char* has_length = \"has length\";\n        char* predicate_max = \"and is the longest string\";\n        char* predicate_min = \"and is the shortest string\";\n        char* predicate_ave = \"and is neither the longest nor the shortest string\";\n\n        int* si = malloc(2 * n * sizeof(int));\n        if (si != NULL)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                si[2 * i] = strlen(strings[i]);\n                si[2 * i + 1] = i;\n            }\n            qsort(si, n, 2 * sizeof(int), cmp);\n\n            int max = si[0];\n            int min = si[2 * (n - 1)];\n\n            for (int i = 0; i < n; i++)\n            {\n                int length = si[2 * i];\n                char* string = strings[si[2 * i + 1]];\n                char* predicate;\n                if (length == max)\n                    predicate = predicate_max;\n                else if (length == min)\n                    predicate = predicate_min;\n                else\n                    predicate = predicate_ave;\n                printf(\"\\\"%s\\\" %s %d %s\\n\",\n                    string, has_length, length, predicate);\n            }\n\n            free(si);\n        }\n        else\n        {\n            fputs(\"unable allocate memory buffer\", stderr);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    char* list[] = { \"abcd\", \"123456789\", \"abcdef\", \"1234567\" };\n\n    compareAndReportStringsLength(list, 4);\n\n    return EXIT_SUCCESS;\n}\n"}
{"id": 45652, "name": "Sorting algorithms_Shell sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n", "C": "#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h /= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a / sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n"}
{"id": 45653, "name": "Doubly-linked list_Definition", "Go": "type dlNode struct {\n    int\n    next, prev *dlNode\n}\n\n\n\n\n\ntype dlList struct {\n    members map[*dlNode]int\n    head, tail **dlNode\n}\n", "C": "\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct List {\n   struct MNode *head;\n   struct MNode *tail;\n   struct MNode *tail_pred;\n};\n\nstruct MNode {\n   struct MNode *succ;\n   struct MNode *pred;\n};\n\ntypedef struct MNode *NODE;\ntypedef struct List *LIST;\n\n\nLIST newList(void);\n\n\nint isEmpty(LIST);\n\n\nNODE getTail(LIST);\n\n\nNODE getHead(LIST);\n\n\nNODE addTail(LIST, NODE);\n\n\nNODE addHead(LIST, NODE);\n\n\nNODE remHead(LIST);\n\n\nNODE remTail(LIST);\n\n\nNODE insertAfter(LIST, NODE, NODE);\n\n\nNODE removeNode(LIST, NODE);\n\n\nLIST newList(void)\n{\n    LIST tl = malloc(sizeof(struct List));\n    if ( tl != NULL )\n    {\n       tl->tail_pred = (NODE)&tl->head;\n       tl->tail = NULL;\n       tl->head = (NODE)&tl->tail;\n       return tl;\n    }\n    return NULL;\n}\n\nint isEmpty(LIST l)\n{\n   return (l->head->succ == 0);\n}\n\nNODE getHead(LIST l)\n{\n  return l->head;\n}\n\nNODE getTail(LIST l)\n{\n  return l->tail_pred;\n}\n\n\nNODE addTail(LIST l, NODE n)\n{\n    n->succ = (NODE)&l->tail;\n    n->pred = l->tail_pred;\n    l->tail_pred->succ = n;\n    l->tail_pred = n;\n    return n;\n}\n\nNODE addHead(LIST l, NODE n)\n{\n    n->succ = l->head;\n    n->pred = (NODE)&l->head;\n    l->head->pred = n;\n    l->head = n;\n    return n;\n}\n\nNODE remHead(LIST l)\n{\n   NODE h;\n   h = l->head;\n   l->head = l->head->succ;\n   l->head->pred = (NODE)&l->head;\n   return h;\n}\n\nNODE remTail(LIST l)\n{\n   NODE t;\n   t = l->tail_pred;\n   l->tail_pred = l->tail_pred->pred;\n   l->tail_pred->succ = (NODE)&l->tail;\n   return t;\n}\n\nNODE insertAfter(LIST l, NODE r, NODE n)\n{\n   n->pred = r; n->succ = r->succ;\n   n->succ->pred = n; r->succ = n;\n   return n;\n}\n\nNODE removeNode(LIST l, NODE n)\n{\n   n->pred->succ = n->succ;\n   n->succ->pred = n->pred;\n   return n;\n}\n"}
{"id": 45654, "name": "Letter frequency", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n", "C": "\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \n\n    \n    if ('a' <= ch && ch <= 'z')      \n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \n        frequency[ch-'A']++;\n}\n"}
{"id": 45655, "name": "Permutation test", "Go": "package main\n\nimport \"fmt\"\n\nvar tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}\nvar ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}\n\nfunc main() {\n    \n    all := make([]int, len(tr)+len(ct))\n    copy(all, tr)\n    copy(all[len(tr):], ct)\n\n    \n    var sumAll int\n    for _, r := range all {\n        sumAll += r\n    }\n\n    \n    \n    \n    sd := func(trc []int) int {\n        var sumTr int\n        for _, x := range trc {\n            sumTr += all[x]\n        }\n        return sumTr*len(ct) - (sumAll-sumTr)*len(tr)\n    }\n\n    \n    a := make([]int, len(tr))\n    for i, _ := range a {\n        a[i] = i\n    }\n    sdObs := sd(a)\n\n    \n    \n    var nLe, nGt int\n    comb(len(all), len(tr), func(c []int) {\n        if sd(c) > sdObs {\n            nGt++\n        } else {\n            nLe++\n        }\n    })\n\n    \n    pc := 100 / float64(nLe+nGt)\n    fmt.Printf(\"differences <= observed: %f%%\\n\", float64(nLe)*pc)\n    fmt.Printf(\"differences  > observed: %f%%\\n\", float64(nGt)*pc)\n}\n\n\nfunc comb(n, m int, emit func([]int)) {\n    s := make([]int, m)\n    last := m - 1\n    var rc func(int, int)\n    rc = func(i, next int) {\n        for j := next; j < n; j++ {\n            s[i] = j\n            if i == last {\n                emit(s)\n            } else {\n                rc(i+1, j+1)\n            }\n        }\n        return\n    }\n    rc(0, 0)\n}\n", "C": "#include <stdio.h>\n\nint data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,\n                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n        if (!remain) return (accu > treat) ? 1 : 0;\n\n        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n        int treat = 0, i;\n        int le, gt;\n        double total = 1;\n        for (i = 0; i < 9; i++) treat += data[i];\n        for (i = 19; i > 10; i--) total *= i;\n        for (i = 9; i > 0; i--) total /= i;\n\n        gt = pick(19, 9, 0, treat);\n        le = total - gt;\n\n        printf(\"<= : %f%%  %d\\n > : %f%%  %d\\n\",\n               100 * le / total, le, 100 * gt / total, gt);\n        return 0;\n}\n"}
{"id": 45656, "name": "Möbius function", "Go": "package main\n\nimport \"fmt\"\n\nfunc möbius(to int) []int {\n    if to < 1 {\n        to = 1\n    }\n    mobs := make([]int, to+1) \n    primes := []int{2}\n    for i := 1; i <= to; i++ {\n        j := i\n        cp := 0      \n        spf := false \n        for _, p := range primes {\n            if p > j {\n                break\n            }\n            if j%p == 0 {\n                j /= p\n                cp++\n            }\n            if j%p == 0 {\n                spf = true\n                break\n            }\n        }\n        if cp == 0 && i > 2 {\n            cp = 1\n            primes = append(primes, i)\n        }\n        if !spf {\n            if cp%2 == 0 {\n                mobs[i] = 1\n            } else {\n                mobs[i] = -1\n            }\n        }\n    }\n    return mobs\n}\n\nfunc main() {\n    mobs := möbius(199)\n    fmt.Println(\"Möbius sequence - First 199 terms:\")\n    for i := 0; i < 200; i++ {\n        if i == 0 {\n            fmt.Print(\"    \")\n            continue\n        }\n        if i%20 == 0 {\n            fmt.Println()\n        }\n        fmt.Printf(\"  % d\", mobs[i])\n    }\n}\n", "C": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n    const int MU_MAX = 1000000;\n    int i, j;\n    int *mu;\n    int sqroot;\n\n    sqroot = (int)sqrt(MU_MAX);\n\n    mu = malloc((MU_MAX + 1) * sizeof(int));\n\n    for (i = 0; i < MU_MAX;i++) {\n        mu[i] = 1;\n    }\n\n    for (i = 2; i <= sqroot; i++) {\n        if (mu[i] == 1) {\n            \n            for (j = i; j <= MU_MAX; j += i) {\n                mu[j] *= -i;\n            }\n            \n            for (j = i * i; j <= MU_MAX; j += i * i) {\n                mu[j] = 0;\n            }\n        }\n    }\n\n    for (i = 2; i <= MU_MAX; i++) {\n        if (mu[i] == i) {\n            mu[i] = 1;\n        } else if (mu[i] == -i) {\n            mu[i] = -1;\n        } else if (mu[i] < 0) {\n            mu[i] = 1;\n        } else if (mu[i] > 0) {\n            mu[i] = -1;\n        }\n    }\n\n    printf(\"First 199 terms of the möbius function are as follows:\\n    \");\n    for (i = 1; i < 200; i++) {\n        printf(\"%2d  \", mu[i]);\n        if ((i + 1) % 20 == 0) {\n            printf(\"\\n\");\n        }\n    }\n\n    free(mu);\n    return 0;\n}\n"}
{"id": 45657, "name": "Increment a numerical string", "Go": "package main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n"}
{"id": 45658, "name": "Strip a set of characters from a string", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n", "C": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n"}
{"id": 45659, "name": "Sorting algorithms_Permutation sort", "Go": "package main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    if len(a) > 1 && !recurse(len(a) - 1) {\n        \n        \n        \n        \n        panic(\"sorted permutation not found!\")\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\nfunc recurse(last int) bool {\n    if last <= 0 {\n        \n        for i := len(a) - 1; a[i] >= a[i-1]; i-- {\n            if i == 1 {\n                return true\n            }\n        }\n        return false\n    }\n    for i := 0; i <= last; i++ {\n        a[i], a[last] = a[last], a[i]\n        if recurse(last - 1) {\n            return true\n        }\n        a[i], a[last] = a[last], a[i]\n    }\n    return false\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef int(*cmp_func)(const void*, const void*);\n\nvoid perm_sort(void *a, int n, size_t msize, cmp_func _cmp)\n{\n\tchar *p, *q, *tmp = malloc(msize);\n#\tdefine A(i) ((char *)a + msize * (i))\n#\tdefine swap(a, b) {\\\n\t\tmemcpy(tmp, a, msize);\\\n\t\tmemcpy(a, b, msize);\\\n\t\tmemcpy(b, tmp, msize);\t}\n\twhile (1) {\n\t\t\n\t\tfor (p = A(n - 1); (void*)p > a; p = q)\n\t\t\tif (_cmp(q = p - msize, p) > 0)\n\t\t\t\tbreak;\n\n\t\tif ((void*)p <= a) break;\n\n\t\t\n\t\tfor (p = A(n - 1); p > q; p-= msize)\n\t\t\tif (_cmp(q, p) > 0) break;\n\n\t\tswap(p, q); \n\t\t\n\t\tfor (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)\n\t\t\tswap(p, q);\n\t}\n\tfree(tmp);\n}\n\nint scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }\n\nint main()\n{\n\tint i;\n\tconst char *strs[] = { \"spqr\", \"abc\", \"giant squid\", \"stuff\", \"def\" };\n\tperm_sort(strs, 5, sizeof(*strs), scmp);\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"%s\\n\", strs[i]);\n\treturn 0;\n}\n"}
{"id": 45660, "name": "Averages_Arithmetic mean", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n    if len(v) == 0 {\n        return\n    }\n    \n    \n    var parts []float64\n    for _, x := range v {\n        var i int\n        for _, p := range parts {\n            sum := p + x\n            var err float64\n            switch ax, ap := math.Abs(x), math.Abs(p); {\n            case ax < ap:\n                err = x - (sum - p)\n            case ap < ax:\n                err = p - (sum - x)\n            }\n            if err != 0 {\n                parts[i] = err\n                i++\n            }\n            x = sum\n        }\n        parts = append(parts[:i], x)\n    }\n    var sum float64\n    for _, x := range parts {\n        sum += x\n    }\n    return sum / float64(len(v)), true\n}\n\nfunc main() {\n    for _, v := range [][]float64{\n        []float64{},                         \n        []float64{math.Inf(1), math.Inf(1)}, \n\n        \n        \n        []float64{math.Inf(1), math.Inf(-1)},\n\n        []float64{3, 1, 4, 1, 5, 9},\n\n        \n        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n    } {\n        fmt.Println(\"Vector:\", v)\n        if m, ok := mean(v); ok {\n            fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n        } else {\n            fmt.Println(\"Mean undefined\\n\")\n        }\n    }\n}\n", "C": "#include <stdio.h>\n\ndouble mean(double *v, int len)\n{\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < len; i++)\n\t\tsum += v[i];\n\treturn sum / len;\n}\n\nint main(void)\n{\n\tdouble v[] = {1, 2, 2.718, 3, 3.142};\n\tint i, len;\n\tfor (len = 5; len >= 0; len--) {\n\t\tprintf(\"mean[\");\n\t\tfor (i = 0; i < len; i++)\n\t\t\tprintf(i ? \", %g\" : \"%g\", v[i]);\n\t\tprintf(\"] = %g\\n\", mean(v, len));\n\t}\n\n\treturn 0;\n}\n"}
{"id": 45661, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 45662, "name": "Abbreviations, simple", "Go": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \" +\n\t\t\"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 \"\n\n\tconst sentence = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n", "C": "#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char* command_table =\n  \"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 \"\n  \"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate \"\n  \"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n  \"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load \"\n  \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 \"\n  \"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 \"\n  \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n  \"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1\";\n\ntypedef struct command_tag {\n    char* cmd;\n    size_t length;\n    size_t min_len;\n    struct command_tag* next;\n} command_t;\n\n\nbool command_match(const command_t* command, const char* str) {\n    size_t olen = strlen(str);\n    return olen >= command->min_len && olen <= command->length\n        && strncmp(str, command->cmd, olen) == 0;\n}\n\n\nchar* uppercase(char* str, size_t n) {\n    for (size_t i = 0; i < n; ++i)\n        str[i] = toupper((unsigned char)str[i]);\n    return str;\n}\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nvoid* xrealloc(void* p, size_t n) {\n    void* ptr = realloc(p, n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nchar** split_into_words(const char* str, size_t* count) {\n    size_t size = 0;\n    size_t capacity = 16;\n    char** words = xmalloc(capacity * sizeof(char*));\n    size_t len = strlen(str);\n    for (size_t begin = 0; begin < len; ) {\n        size_t i = begin;\n        for (; i < len && isspace((unsigned char)str[i]); ++i) {}\n        begin = i;\n        for (; i < len && !isspace((unsigned char)str[i]); ++i) {}\n        size_t word_len = i - begin;\n        if (word_len == 0)\n            break;\n        char* word = xmalloc(word_len + 1);\n        memcpy(word, str + begin, word_len);\n        word[word_len] = 0;\n        begin += word_len;\n        if (capacity == size) {\n            capacity *= 2;\n            words = xrealloc(words, capacity * sizeof(char*));\n        }\n        words[size++] = word;\n    }\n    *count = size;\n    return words;\n}\n\ncommand_t* make_command_list(const char* table) {\n    command_t* cmd = NULL;\n    size_t count = 0;\n    char** words = split_into_words(table, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        command_t* new_cmd = xmalloc(sizeof(command_t));\n        size_t word_len = strlen(word);\n        new_cmd->length = word_len;\n        new_cmd->min_len = word_len;\n        new_cmd->cmd = uppercase(word, word_len);\n        if (i + 1 < count) {\n            char* eptr = 0;\n            unsigned long min_len = strtoul(words[i + 1], &eptr, 10);\n            if (min_len > 0 && *eptr == 0) {\n                free(words[i + 1]);\n                new_cmd->min_len = min_len;\n                ++i;\n            }\n        }\n        new_cmd->next = cmd;\n        cmd = new_cmd;\n    }\n    free(words);\n    return cmd;\n}\n\nvoid free_command_list(command_t* cmd) {\n    while (cmd != NULL) {\n        command_t* next = cmd->next;\n        free(cmd->cmd);\n        free(cmd);\n        cmd = next;\n    }\n}\n\nconst command_t* find_command(const command_t* commands, const char* word) {\n    for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {\n        if (command_match(cmd, word))\n            return cmd;\n    }\n    return NULL;\n}\n\nvoid test(const command_t* commands, const char* input) {\n    printf(\" input: %s\\n\", input);\n    printf(\"output:\");\n    size_t count = 0;\n    char** words = split_into_words(input, &count);\n    for (size_t i = 0; i < count; ++i) {\n        char* word = words[i];\n        uppercase(word, strlen(word));\n        const command_t* cmd_ptr = find_command(commands, word);\n        printf(\" %s\", cmd_ptr ? cmd_ptr->cmd : \"*error*\");\n        free(word);\n    }\n    free(words);\n    printf(\"\\n\");\n}\n\nint main() {\n    command_t* commands = make_command_list(command_table);\n    const char* input = \"riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin\";\n    test(commands, input);\n    free_command_list(commands);\n    return 0;\n}\n"}
{"id": 45663, "name": "Entropy", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strings\"\n)\n\nfunc main(){\n    fmt.Println(H(\"1223334444\"))\n}\n\n\nfunc H(data string) (entropy float64) {\n    if data == \"\" {\n        return 0\n    }\n    for i := 0; i < 256; i++ {\n        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))\n        if px > 0 {\n\t    entropy += -px * math.Log2(px)\n\t}\n    }\n    return entropy\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n \n#define MAXLEN 100 \n \nint makehist(unsigned char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n \ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n \nint main(void){\n\tunsigned char S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tscanf(\"%[^\\n]\",S);\n\tlen=strlen(S);\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 45664, "name": "Tokenize a string with escaping", "Go": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc TokenizeString(s string, sep, escape rune) (tokens []string, err error) {\n\tvar runes []rune\n\tinEscape := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase inEscape:\n\t\t\tinEscape = false\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\trunes = append(runes, r)\n\t\tcase r == escape:\n\t\t\tinEscape = true\n\t\tcase r == sep:\n\t\t\ttokens = append(tokens, string(runes))\n\t\t\trunes = runes[:0]\n\t\t}\n\t}\n\ttokens = append(tokens, string(runes))\n\tif inEscape {\n\t\terr = errors.New(\"invalid terminal escape\")\n\t}\n\treturn tokens, err\n}\n\nfunc main() {\n\tconst sample = \"one^|uno||three^^^^|four^^^|^cuatro|\"\n\tconst separator = '|'\n\tconst escape = '^'\n\n\tfmt.Printf(\"Input:   %q\\n\", sample)\n\ttokens, err := TokenizeString(sample, separator, escape)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t} else {\n\t\tfmt.Printf(\"Tokens: %q\\n\", tokens)\n\t}\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\n#define STR_DEMO \"one^|uno||three^^^^|four^^^|^cuatro|\"\n#define SEP '|'\n#define ESC '^'\n\ntypedef char* Str; \n\n\nunsigned int ElQ( const char *s, char sep, char esc );\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q );\n\n\n\nint main() {\n    char s[] = STR_DEMO;\n    unsigned int i, q;\n\n    Str *list = Tokenize( s, SEP, ESC, &q );\n\n    if( list != NULL ) {\n        printf( \"\\n Original string: %s\\n\\n\", STR_DEMO );\n        printf( \" %d tokens:\\n\\n\", q );\n\n        for( i=0; i<q; ++i )\n            printf( \" %4d. %s\\n\", i+1, list[i] );\n\n        free( list );\n    }\n\n    return 0;\n}\n\n\n\nunsigned int ElQ( const char *s, char sep, char esc ) {\n    unsigned int q, e;\n    const char *p;\n\n    for( e=0, q=1, p=s; *p; ++p ) {\n        if( *p == esc )\n            e = !e;\n        else if( *p == sep )\n            q += !e;\n        else e = 0;\n    }\n\n    return q;\n}\n\n\n\nStr *Tokenize( char *s, char sep, char esc, unsigned int *q ) {\n    Str *list = NULL;\n\n    *q = ElQ( s, sep, esc );\n    list = malloc( *q * sizeof(Str) );\n\n    if( list != NULL ) {\n        unsigned int e, i;\n        char *p;\n\n        i = 0;\n        list[i++] = s;\n\n        for( e=0, p=s; *p; ++p ) {\n            if( *p == esc ) {\n                e = !e;\n            }\n            else if( *p == sep && !e ) {\n                list[i++] = p+1;\n                *p = '\\0';\n            }\n            else {\n                e = 0;\n            }\n        }\n    }\n\n    return list;\n}\n"}
{"id": 45665, "name": "Hello world_Text", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"Hello world!\") }\n", "C": "const hello = \"Hello world!\\n\"\n\nprint(hello)\n"}
{"id": 45666, "name": "Sexy primes", "Go": "package main\n\nimport \"fmt\"\n\nfunc sieve(limit int) []bool {\n    limit++\n    \n    c := make([]bool, limit) \n    c[0] = true\n    c[1] = true\n    \n    p := 3 \n    for {\n        p2 := p * p\n        if p2 >= limit {\n            break\n        }\n        for i := p2; i < limit; i += 2 * p {\n            c[i] = true\n        }\n        for {\n            p += 2\n            if !c[p] {\n                break\n            }\n        }\n    }\n    return c\n}\n\nfunc commatize(n int) string {\n    s := fmt.Sprintf(\"%d\", n)\n    if n < 0 {\n        s = s[1:]\n    }\n    le := len(s)\n    for i := le - 3; i >= 1; i -= 3 {\n        s = s[0:i] + \",\" + s[i:]\n    }\n    if n >= 0 {\n        return s\n    }\n    return \"-\" + s\n}\n\nfunc printHelper(cat string, le, lim, max int) (int, int, string) {\n    cle, clim := commatize(le), commatize(lim)\n    if cat != \"unsexy primes\" {\n        cat = \"sexy prime \" + cat\n    }\n    fmt.Printf(\"Number of %s less than %s = %s\\n\", cat, clim, cle)\n    last := max\n    if le < last {\n        last = le\n    }\n    verb := \"are\"\n    if last == 1 {\n        verb = \"is\"\n    }\n    return le, last, verb\n}\n\nfunc main() {\n    lim := 1000035\n    sv := sieve(lim - 1)\n    var pairs [][2]int\n    var trips [][3]int\n    var quads [][4]int\n    var quins [][5]int\n    var unsexy = []int{2, 3}\n    for i := 3; i < lim; i += 2 {\n        if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {\n            unsexy = append(unsexy, i)\n            continue\n        }\n        if i < lim-6 && !sv[i] && !sv[i+6] {\n            pair := [2]int{i, i + 6}\n            pairs = append(pairs, pair)\n        } else {\n            continue\n        }\n        if i < lim-12 && !sv[i+12] {\n            trip := [3]int{i, i + 6, i + 12}\n            trips = append(trips, trip)\n        } else {\n            continue\n        }\n        if i < lim-18 && !sv[i+18] {\n            quad := [4]int{i, i + 6, i + 12, i + 18}\n            quads = append(quads, quad)\n        } else {\n            continue\n        }\n        if i < lim-24 && !sv[i+24] {\n            quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}\n            quins = append(quins, quin)\n        }\n    }\n    le, n, verb := printHelper(\"pairs\", len(pairs), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, pairs[le-n:])\n\n    le, n, verb = printHelper(\"triplets\", len(trips), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, trips[le-n:])\n\n    le, n, verb = printHelper(\"quadruplets\", len(quads), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quads[le-n:])\n\n    le, n, verb = printHelper(\"quintuplets\", len(quins), lim, 5)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, quins[le-n:])\n\n    le, n, verb = printHelper(\"unsexy primes\", len(unsexy), lim, 10)\n    fmt.Printf(\"The last %d %s:\\n  %v\\n\\n\", n, verb, unsexy[le-n:])\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n\n#define TRUE 1\n#define FALSE 0\n\ntypedef unsigned char bool;\n\nvoid sieve(bool *c, int limit) {\n    int i, p = 3, p2;\n    \n    c[0] = TRUE;\n    c[1] = TRUE;\n    \n    for (;;) {\n        p2 = p * p;\n        if (p2 >= limit) {\n            break;\n        }\n        for (i = p2; i < limit; i += 2*p) {\n            c[i] = TRUE;\n        }\n        for (;;) {\n            p += 2;\n            if (!c[p]) {\n                break;\n            }\n        }\n    }\n}\n\nvoid printHelper(const char *cat, int len, int lim, int n) {\n    const char *sp = strcmp(cat, \"unsexy primes\") ? \"sexy prime \" : \"\";\n    const char *verb = (len == 1) ? \"is\" : \"are\";\n    printf(\"Number of %s%s less than %'d = %'d\\n\", sp, cat, lim, len);\n    printf(\"The last %d %s:\\n\", n, verb);\n}\n\nvoid printArray(int *a, int len) {\n    int i;\n    printf(\"[\");\n    for (i = 0; i < len; ++i) printf(\"%d \", a[i]);\n    printf(\"\\b]\");\n}\n\nint main() {\n    int i, ix, n, lim = 1000035;\n    int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;\n    int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;\n    int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;\n    int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];\n    int last_un[10];\n    bool *sv = calloc(lim - 1, sizeof(bool)); \n    setlocale(LC_NUMERIC, \"\");\n    sieve(sv, lim);\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            unsexy++;\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pairs++;\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            trips++;\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            quads++;\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            quins++;\n        }\n    }\n    if (pairs < lpr) lpr = pairs;\n    if (trips < ltr) ltr = trips;\n    if (quads < lqd) lqd = quads;\n    if (quins < lqn) lqn = quins;\n    if (unsexy < lun) lun = unsexy;\n\n    \n    for (i = 3; i < lim; i += 2) {\n        if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {\n            un++;\n            if (un > unsexy - lun) {\n                last_un[un + lun - 1 - unsexy] = i;\n            }\n            continue;\n        }\n        if (i < lim-6 && !sv[i] && !sv[i+6]) {\n            pr++;\n            if (pr > pairs - lpr) {\n                ix = pr + lpr - 1 - pairs;\n                last_pr[ix][0] = i; last_pr[ix][1] = i + 6;\n            }\n        } else continue;\n\n        if (i < lim-12 && !sv[i+12]) {\n            tr++;\n            if (tr > trips - ltr) {\n                ix = tr + ltr - 1 - trips;\n                last_tr[ix][0] = i; last_tr[ix][1] = i + 6;\n                last_tr[ix][2] = i + 12;\n            }\n        } else continue;\n\n        if (i < lim-18 && !sv[i+18]) {\n            qd++;\n            if (qd > quads - lqd) {\n                ix = qd + lqd - 1 - quads;\n                last_qd[ix][0] = i; last_qd[ix][1] = i + 6;\n                last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;\n            }\n        } else continue;\n\n        if (i < lim-24 && !sv[i+24]) {\n            qn++;\n            if (qn > quins - lqn) {\n                ix = qn + lqn - 1 - quins;\n                last_qn[ix][0] = i; last_qn[ix][1] = i + 6;\n                last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;\n                last_qn[ix][4] = i + 24;\n            }\n        }\n    }\n\n    printHelper(\"pairs\", pairs, lim, lpr);\n    printf(\"  [\");\n    for (i = 0; i < lpr; ++i) {\n        printArray(last_pr[i], 2);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"triplets\", trips, lim, ltr);\n    printf(\"  [\");\n    for (i = 0; i < ltr; ++i) {\n        printArray(last_tr[i], 3);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quadruplets\", quads, lim, lqd);\n    printf(\"  [\");\n    for (i = 0; i < lqd; ++i) {\n        printArray(last_qd[i], 4);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"quintuplets\", quins, lim, lqn);\n    printf(\"  [\");\n    for (i = 0; i < lqn; ++i) {\n        printArray(last_qn[i], 5);\n        printf(\"\\b] \");\n    }\n    printf(\"\\b]\\n\\n\");\n\n    printHelper(\"unsexy primes\", unsexy, lim, lun);\n    printf(\"  [\");\n    printArray(last_un, lun);\n    printf(\"\\b]\\n\");\n    free(sv);\n    return 0;\n}\n"}
{"id": 45667, "name": "Forward difference", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}\n    fmt.Println(a)\n    fmt.Println(fd(a, 9))\n}\n\nfunc fd(a []int, ord int) []int {\n    for i := 0; i < ord; i++ {\n        for j := 0; j < len(a)-i-1; j++ {\n            a[j] = a[j+1] - a[j]\n        }\n    }\n    return a[:len(a)-ord]\n}\n", "C": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\ndouble* fwd_diff(double* x, unsigned int len, unsigned int order)\n{\n\tunsigned int i, j;\n\tdouble* y;\n\n\t\n\tif (order >= len) return 0;\n\n\ty = malloc(sizeof(double) * len);\n\tif (!order) {\n\t\tmemcpy(y, x, sizeof(double) * len);\n\t\treturn y;\n\t}\n\n\t\n\tfor (j = 0; j < order; j++, x = y)\n\t\tfor (i = 0, len--; i < len; i++)\n\t\t\ty[i] = x[i + 1] - x[i];\n\n\ty = realloc(y, sizeof(double) * len);\n\treturn y;\n}\n\nint main(void)\n{\n\tdouble *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};\n\tint i, len = sizeof(x) / sizeof(x[0]);\n\n\ty = fwd_diff(x, len, 1);\n\tfor (i = 0; i < len - 1; i++)\n\t\tprintf(\"%g \", y[i]);\n\tputchar('\\n');\n\n\treturn 0;\n}\n"}
{"id": 45668, "name": "Primality by trial division", "Go": "func IsPrime(n int) bool {\n\tif n < 0 { n = -n }\n\tswitch {\n        case n == 2:\n\t\treturn true\n\tcase n < 2 || n % 2 == 0:\n\t\treturn false\n\t\n\tdefault:\n\t\tfor i = 3; i*i <= n; i += 2 {\n\t\t\tif n % i == 0 { return false }\n\t\t}\n\t}\n\treturn true\n}\n", "C": "int is_prime(unsigned int n)\n{\n\tunsigned int p;\n\tif (!(n & 1) || n < 2 ) return n == 2;\n\n\t\n\tfor (p = 3; p <= n/p; p += 2)\n\t\tif (!(n % p)) return 0;\n\treturn 1;\n}\n"}
{"id": 45669, "name": "Evaluate binomial coefficients", "Go": "package main\nimport \"fmt\"\nimport \"math/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n", "C": "#include <stdio.h>\n#include <limits.h>\n\n\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX/n) {  \n      unsigned long nr, dr;  \n      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;\n      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;\n      if (r >= ULONG_MAX/nr) return 0;  \n      r *= nr;\n      r /= dr;\n      n--;\n    } else {\n      r *= n--;\n      r /= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n"}
{"id": 45670, "name": "Collections", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n", "C": "#define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) \nint ar[10];               \nar[0] = 1;                \nar[1] = 2;\n\nint* p;                   \nfor (p=ar;                \n       p<(ar+cSize(ar));  \n       p++) {             \n  printf(\"%d\\n\",*p);      \n}                         \n"}
{"id": 45671, "name": "Singly-linked list_Traversal", "Go": "start := &Ele{\"tacos\", nil}\nend := start.Append(\"burritos\")\nend = end.Append(\"fajitas\")\nend = end.Append(\"enchilatas\")\nfor iter := start; iter != nil; iter = iter.Next {\n    fmt.Println(iter)\n}\n", "C": "struct link *first;\n\nstruct link *iter;\nfor(iter = first; iter != NULL; iter = iter->next) {\n  \n}\n"}
{"id": 45672, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 45673, "name": "Bitmap_Write a PPM file", "Go": "package raster\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\n\nfunc (b *Bitmap) WritePpmTo(w io.Writer) (err error) {\n    \n    if _, err = fmt.Fprintln(w, \"P6\"); err != nil {\n        return\n    }\n\n    \n    for _, c := range b.Comments {\n        if _, err = fmt.Fprintln(w, c); err != nil {\n            return\n        }\n    }\n\n    \n    _, err = fmt.Fprintf(w, \"%d %d\\n255\\n\", b.cols, b.rows)\n    if err != nil {\n        return\n    }\n\n    \n    b3 := make([]byte, 3*len(b.px))\n    n1 := 0\n    for _, px := range b.px {\n        b3[n1] = px.R\n        b3[n1+1] = px.G\n        b3[n1+2] = px.B\n        n1 += 3\n    }\n    if _, err = w.Write(b3); err != nil {\n        return\n    }\n    return\n}\n\n\nfunc (b *Bitmap) WritePpmFile(fn string) (err error) {\n    var f *os.File\n    if f, err = os.Create(fn); err != nil {\n        return\n    }\n    if err = b.WritePpmTo(f); err != nil {\n        return\n    }\n    return f.Close()\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(void)\n{\n  const int dimx = 800, dimy = 800;\n  int i, j;\n  FILE *fp = fopen(\"first.ppm\", \"wb\"); \n  (void) fprintf(fp, \"P6\\n%d %d\\n255\\n\", dimx, dimy);\n  for (j = 0; j < dimy; ++j)\n  {\n    for (i = 0; i < dimx; ++i)\n    {\n      static unsigned char color[3];\n      color[0] = i % 256;  \n      color[1] = j % 256;  \n      color[2] = (i * j) % 256;  \n      (void) fwrite(color, 1, 3, fp);\n    }\n  }\n  (void) fclose(fp);\n  return EXIT_SUCCESS;\n}\n"}
{"id": 45674, "name": "Delete a file", "Go": "package main\nimport \"os\"\n\nfunc main() {\n  os.Remove(\"input.txt\")\n  os.Remove(\"/input.txt\")\n  os.Remove(\"docs\")\n  os.Remove(\"/docs\")\n  \n  os.RemoveAll(\"docs\")\n  os.RemoveAll(\"/docs\")\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  remove(\"input.txt\");\n  remove(\"/input.txt\");\n  remove(\"docs\");\n  remove(\"/docs\");\n  return 0;\n}\n"}
{"id": 45675, "name": "Discordian date", "Go": "package ddate\n\nimport (\n    \"strconv\"\n    \"strings\" \n    \"time\"\n)   \n    \n\nconst (\n    DefaultFmt = \"Pungenday, Discord 5, 3131 YOLD\"\n    OldFmt     = `Today is Pungenday, the 5th day of Discord in the YOLD 3131\nCelebrate Mojoday`\n)\n\n\n\n\n\n\nconst (\n    protoLongSeason  = \"Discord\"\n    protoShortSeason = \"Dsc\"\n    protoLongDay     = \"Pungenday\"\n    protoShortDay    = \"PD\"\n    protoOrdDay      = \"5\"\n    protoCardDay     = \"5th\"\n    protoHolyday     = \"Mojoday\"\n    protoYear        = \"3131\"\n)\n\nvar (\n    longDay = []string{\"Sweetmorn\", \"Boomtime\", \"Pungenday\",\n        \"Prickle-Prickle\", \"Setting Orange\"}\n    shortDay   = []string{\"SM\", \"BT\", \"PD\", \"PP\", \"SO\"}\n    longSeason = []string{\n        \"Chaos\", \"Discord\", \"Confusion\", \"Bureaucracy\", \"The Aftermath\"}\n    shortSeason = []string{\"Chs\", \"Dsc\", \"Cfn\", \"Bcy\", \"Afm\"}\n    holyday     = [][]string{{\"Mungday\", \"Chaoflux\"}, {\"Mojoday\", \"Discoflux\"},\n        {\"Syaday\", \"Confuflux\"}, {\"Zaraday\", \"Bureflux\"}, {\"Maladay\", \"Afflux\"}}\n)   \n    \ntype DiscDate struct {\n    StTibs bool\n    Dayy   int \n    Year   int \n}\n\nfunc New(eris time.Time) DiscDate {\n    t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),\n        eris.Second(), eris.Nanosecond(), eris.Location())\n    bob := int(eris.Sub(t).Hours()) / 24\n    raw := eris.Year()\n    hastur := DiscDate{Year: raw + 1166}\n    if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {\n        if bob > 59 {\n            bob--\n        } else if bob == 59 {\n            hastur.StTibs = true\n            return hastur\n        }\n    }\n    hastur.Dayy = bob\n    return hastur\n}\n\nfunc (dd DiscDate) Format(f string) (r string) {\n    var st, snarf string\n    var dateElement bool\n    f6 := func(proto, wibble string) {\n        if !dateElement {\n            snarf = r\n            dateElement = true\n        }\n        if st > \"\" {\n            r = \"\"\n        } else {\n            r += wibble\n        }\n        f = f[len(proto):]\n    }\n    f4 := func(proto, wibble string) {\n        if dd.StTibs {\n            st = \"St. Tib's Day\"\n        }\n        f6(proto, wibble)\n    }\n    season, day := dd.Dayy/73, dd.Dayy%73\n    for f > \"\" {\n        switch {\n        case strings.HasPrefix(f, protoLongDay):\n            f4(protoLongDay, longDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoShortDay):\n            f4(protoShortDay, shortDay[dd.Dayy%5])\n        case strings.HasPrefix(f, protoCardDay):\n            funkychickens := \"th\"\n            if day/10 != 1 {\n                switch day % 10 {\n                case 0:\n                    funkychickens = \"st\"\n                case 1:\n                    funkychickens = \"nd\"\n                case 2:\n                    funkychickens = \"rd\"\n                }\n            }\n            f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)\n        case strings.HasPrefix(f, protoOrdDay):\n            f4(protoOrdDay, strconv.Itoa(day+1))\n        case strings.HasPrefix(f, protoLongSeason):\n            f6(protoLongSeason, longSeason[season])\n        case strings.HasPrefix(f, protoShortSeason):\n            f6(protoShortSeason, shortSeason[season])\n        case strings.HasPrefix(f, protoHolyday):\n            if day == 4 {\n                r += holyday[season][0]\n            } else if day == 49 {\n                r += holyday[season][1]\n            }\n            f = f[len(protoHolyday):]\n        case strings.HasPrefix(f, protoYear):\n            r += strconv.Itoa(dd.Year)\n            f = f[4:]\n        default:\n            r += f[:1]\n            f = f[1:]\n        }\n    }\n    if st > \"\" { \n        r = snarf + st + r\n    }\n    return\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n \n#define day_of_week( x ) ((x) == 1 ? \"Sweetmorn\" :\\\n                          (x) == 2 ? \"Boomtime\" :\\\n                          (x) == 3 ? \"Pungenday\" :\\\n                          (x) == 4 ? \"Prickle-Prickle\" :\\\n                          \"Setting Orange\")\n \n#define season( x ) ((x) == 0 ? \"Chaos\" :\\\n                    (x) == 1 ? \"Discord\" :\\\n                    (x) == 2 ? \"Confusion\" :\\\n                    (x) == 3 ? \"Bureaucracy\" :\\\n                    \"The Aftermath\")\n \n#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)\n \n#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))\n \nchar * ddate( int y, int d ){\n  int dyear = 1166 + y;\n  char * result = malloc( 100 * sizeof( char ) );\n \n  if( leap_year( y ) ){\n    if( d == 60 ){\n      sprintf( result, \"St. Tib's Day, YOLD %d\", dyear );\n      return result;\n    } else if( d >= 60 ){\n      -- d;\n    }\n  }\n \n  sprintf( result, \"%s, %s %d, YOLD %d\",\n           day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );\n \n  return result;\n}\n \n \nint day_of_year( int y, int m, int d ){\n  int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n \n  for( ; m > 1; m -- ){\n    d += month_lengths[ m - 2 ];\n    if( m == 3 && leap_year( y ) ){\n      ++ d;\n    }\n  }\n  return d;\n}\n \n \nint main( int argc, char * argv[] ){\n  time_t now;\n  struct tm * now_time;\n  int year, doy;\n \n  if( argc == 1 ){\n    now = time( NULL );\n    now_time = localtime( &now );\n    year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;\n  } else if( argc == 4 ){\n    year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );\n  }\n \n  char * result = ddate( year, doy );\n  puts( result );\n  free( result );\n \n  return 0;\n}\n"}
{"id": 45676, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"}
{"id": 45677, "name": "Flipping bits game", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n    \n\tvar n int = 3 \n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n    b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c)  1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\"   \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint i, j;\n\nvoid fliprow(int **b, int sz, int n)\n{\n\tfor(i = 0; i < sz; i++)\n\t\tb[n+1][i] = !b[n+1][i];\n}\n\nvoid flipcol(int **b, int sz, int n)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i][n] = !b[i][n];\n}\n\nvoid initt(int **t, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tt[i][j] = rand()%2;\n}\n\nvoid initb(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tb[i][j] = t[i][j];\n\t\n\tfor(i = 1; i <= sz; i++)\n\t\tfliprow(b, sz, rand()%sz+1);\n\tfor(i = 0; i < sz; i++)\n\t\tflipcol(b, sz, rand()%sz);\n}\n\nvoid printb(int **b, int sz)\n{\n\tprintf(\" \");\n\tfor(i = 0; i < sz; i++)\n\t\tprintf(\" %d\", i);\n\tprintf(\"\\n\");\n\n\tfor(i = 1; i <= sz; i++)\n\t{\n\t\tprintf(\"%d\", i-1);\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tprintf(\" %d\", b[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint eq(int **t, int **b, int sz)\n{\n\tfor(i = 1; i <= sz; i++)\n\t\tfor(j = 0; j < sz; j++)\n\t\t\tif(b[i][j] != t[i][j])\n\t\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid main()\n{\n\tint sz = 3;\n\tint eql = 0;\n\tint mov = 0;\n\tint **t = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tt[i] = malloc(sz*sizeof(int));\n\n\tint **b = malloc(sz*(sizeof(int)+1));\n\tfor(i = 1; i <= sz; i++)\n\t\tb[i] = malloc(sz*sizeof(int));\n\tchar roc;\n\tint n;\n\tinitt(t, sz);\n\tinitb(t, b, sz);\n\t\n\twhile(eq(t, b, sz))\n\t\tinitb(t, b, sz);\n\t\n\twhile(!eql)\n\t{\n\t\tprintf(\"Target: \\n\");\n\t\tprintb(t, sz);\n\t\tprintf(\"Board: \\n\");\n\t\tprintb(b, sz);\n\t\tprintf(\"What to flip: \");\n\t\tscanf(\" %c\", &roc);\n\t\tscanf(\" %d\", &n);\n\n\t\tswitch(roc)\n\t\t{\n\t\t\tcase 'r':\n\t\t\t\tfliprow(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tflipcol(b, sz, n);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"Please specify r or c and an number\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"Moves Taken: %d\\n\", ++mov);\n\n\t\tif(eq(t, b, sz))\n\t\t{\n\t\t\tprintf(\"You win!\\n\");\n\t\t\teql = 1;\n\t\t}\n\t}\n}\n"}
{"id": 45678, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n"}
{"id": 45679, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n"}
{"id": 45680, "name": "Hickerson series of almost integers", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n    h := big.NewRat(1, 2)\n    h.Quo(h, ln2)\n    var f big.Rat\n    var w big.Int\n    for i := int64(1); i <= 17; i++ {\n        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n        w.Quo(h.Num(), h.Denom())\n        f.Sub(h, f.SetInt(&w))\n        y, _ := f.Float64()\n        d := fmt.Sprintf(\"%.3f\", y)\n        fmt.Printf(\"n: %2d  h: %18d%s  Nearly integer: %t\\n\",\n            i, &w, d[1:], d[2] == '0' || d[2] == '9')\n    }\n}\n", "C": "#include <stdio.h>\n#include <mpfr.h>\n\nvoid h(int n)\n{\n\tMPFR_DECL_INIT(a, 200);\n\tMPFR_DECL_INIT(b, 200);\n\n\tmpfr_fac_ui(a, n, MPFR_RNDD);\t\t\n\n\tmpfr_set_ui(b, 2, MPFR_RNDD);\t\t\n\tmpfr_log(b, b, MPFR_RNDD);\t\t\n\tmpfr_pow_ui(b, b, n + 1, MPFR_RNDD);\t\n\n\tmpfr_div(a, a, b, MPFR_RNDD);\t\t\n\tmpfr_div_ui(a, a, 2, MPFR_RNDD);\t\n\n\tmpfr_frac(b, a, MPFR_RNDD);\t\t\n\tmpfr_printf(\"%2d: %23.4Rf  %c\\n\", n, a,\n\t\tmpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');\n}\n\nint main(void)\n{\n\tint n;\n\tfor (n = 1; n <= 17; n++) h(n);\n\n\treturn 0;\n}\n"}
{"id": 45681, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 45682, "name": "Average loop length", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n    fmt.Println(\" N    average    analytical    (error)\")\n    fmt.Println(\"===  =========  ============  =========\")\n    for n := 1; n <= nmax; n++ {\n        a := avg(n)\n        b := ana(n)\n        fmt.Printf(\"%3d  %9.4f  %12.4f  (%6.2f%%)\\n\",\n            n, a, b, math.Abs(a-b)/b*100)\n    }\n}\n\nfunc avg(n int) float64 {\n    const tests = 1e4\n    sum := 0\n    for t := 0; t < tests; t++ {\n        var v [nmax]bool\n        for x := 0; !v[x]; x = rand.Intn(n) {\n            v[x] = true\n            sum++\n        }\n    }\n    return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n    nn := float64(n)\n    term := 1.\n    sum := 1.\n    for i := nn - 1; i >= 1; i-- {\n        term *= i / nn\n        sum += term\n    }\n    return sum\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n#define MAX_N 20\n#define TIMES 1000000\n\ndouble factorial(int n) {\n\tdouble f = 1;\n\tint i;\n\tfor (i = 1; i <= n; i++) f *= i;\n\treturn f;\n}\n\ndouble expected(int n) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 1; i <= n; i++)\n\t\tsum += factorial(n) / pow(n, i) / factorial(n - i);\n\treturn sum;\n}\n\nint randint(int n) {\n\tint r, rmax = RAND_MAX / n * n;\n\twhile ((r = rand()) >= rmax);\n\treturn r / (RAND_MAX / n);\n}\n\nint test(int n, int times) {\n\tint i, count = 0;\n\tfor (i = 0; i < times; i++) {\n\t\tint x = 1, bits = 0;\n\t\twhile (!(bits & x)) {\n\t\t\tcount++;\n\t\t\tbits |= x;\n\t\t\tx = 1 << randint(n);\n\t\t}\n\t}\n\treturn count;\n}\n\nint main(void) {\n\tsrand(time(0));\n\tputs(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n\tint n;\n\tfor (n = 1; n <= MAX_N; n++) {\n\t\tint cnt = test(n, TIMES);\n\t\tdouble avg = (double)cnt / TIMES;\n\t\tdouble theory = expected(n);\n\t\tdouble diff = (avg / theory - 1) * 100;\n\t\tprintf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, avg, theory, diff);\n\t}\n\treturn 0;\n}\n"}
{"id": 45683, "name": "String interpolation (included)", "Go": "package main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    str := \"Mary had a %s lamb\"\n    txt := \"little\"\n    out := fmt.Sprintf(str, txt)\n    fmt.Println(out)\n}\n", "C": "#include <stdio.h>\n\nint main() {\n  const char *extra = \"little\";\n  printf(\"Mary had a %s lamb.\\n\", extra);\n  return 0;\n}\n"}
{"id": 45684, "name": "Sorting algorithms_Patience sort", "Go": "package main\n\nimport (\n  \"fmt\"\n  \"container/heap\"\n  \"sort\"\n)\n\ntype IntPile []int\nfunc (self IntPile) Top() int { return self[len(self)-1] }\nfunc (self *IntPile) Pop() int {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\ntype IntPilesHeap []IntPile\nfunc (self IntPilesHeap) Len() int { return len(self) }\nfunc (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }\nfunc (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }\nfunc (self *IntPilesHeap) Pop() interface{} {\n    x := (*self)[len(*self)-1]\n    *self = (*self)[:len(*self)-1]\n    return x\n}\n\nfunc patience_sort (n []int) {\n  var piles []IntPile\n  \n  for _, x := range n {\n    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })\n    if j != len(piles) {\n      piles[j] = append(piles[j], x)\n    } else {\n      piles = append(piles, IntPile{ x })\n    }\n  }\n\n  \n  hp := IntPilesHeap(piles)\n  heap.Init(&hp)\n  for i, _ := range n {\n    smallPile := heap.Pop(&hp).(IntPile)\n    n[i] = smallPile.Pop()\n    if len(smallPile) != 0 {\n      heap.Push(&hp, smallPile)\n    }\n  }\n  if len(hp) != 0 {\n    panic(\"something went wrong\")\n  }\n}\n\nfunc main() {\n    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}\n    patience_sort(a)\n    fmt.Println(a)\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n\nint* patienceSort(int* arr,int size){\n\tint decks[size][size],i,j,min,pickedRow;\n\t\n\tint *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){\n\t\t\t\tdecks[j][count[j]] = arr[i];\n\t\t\t\tcount[j]++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmin = decks[0][count[0]-1];\n\tpickedRow = 0;\n\t\n\tfor(i=0;i<size;i++){\n\t\tfor(j=0;j<size;j++){\n\t\t\tif(count[j]>0 && decks[j][count[j]-1]<min){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t}\n\t\t}\n\t\tsortedArr[i] = min;\n\t\tcount[pickedRow]--;\n\t\t\n\t\tfor(j=0;j<size;j++)\n\t\t\tif(count[j]>0){\n\t\t\t\tmin = decks[j][count[j]-1];\n\t\t\t\tpickedRow = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\t\n\tfree(count);\n\tfree(decks);\n\t\n\treturn sortedArr;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr, *sortedArr, i;\n\t\n\tif(argC==0)\n\t\tprintf(\"Usage : %s <integers to be sorted separated by space>\");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i<=argC;i++)\n\t\t\tarr[i-1] = atoi(argV[i]);\n\t\t\n\t\tsortedArr = patienceSort(arr,argC-1);\n\t\t\n\t\tfor(i=0;i<argC-1;i++)\n\t\t\tprintf(\"%d \",sortedArr[i]);\n\t}\n\t\n\treturn 0;\n}\n"}
{"id": 45685, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 45686, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 45687, "name": "Bioinformatics_Sequence mutation", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"sort\"\n    \"time\"\n)\n\nconst bases = \"ACGT\"\n\n\n\nfunc mutate(dna string, w [3]int) string {\n    le := len(dna)\n    \n    p := rand.Intn(le)\n    \n    r := rand.Intn(300)\n    bytes := []byte(dna)\n    switch {\n    case r < w[0]: \n        base := bases[rand.Intn(4)]\n        fmt.Printf(\"  Change @%3d %q to %q\\n\", p, bytes[p], base)\n        bytes[p] = base\n    case r < w[0]+w[1]: \n        fmt.Printf(\"  Delete @%3d %q\\n\", p, bytes[p])\n        copy(bytes[p:], bytes[p+1:])\n        bytes = bytes[0 : le-1]\n    default: \n        base := bases[rand.Intn(4)]\n        bytes = append(bytes, 0)\n        copy(bytes[p+1:], bytes[p:])\n        fmt.Printf(\"  Insert @%3d %q\\n\", p, base)\n        bytes[p] = base\n    }\n    return string(bytes)\n}\n\n\nfunc generate(le int) string {\n    bytes := make([]byte, le)\n    for i := 0; i < le; i++ {\n        bytes[i] = bases[rand.Intn(4)]\n    }\n    return string(bytes)\n}\n\n\nfunc prettyPrint(dna string, rowLen int) {\n    fmt.Println(\"SEQUENCE:\")\n    le := len(dna)\n    for i := 0; i < le; i += rowLen {\n        k := i + rowLen\n        if k > le {\n            k = le\n        }\n        fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n    }\n    baseMap := make(map[byte]int) \n    for i := 0; i < le; i++ {\n        baseMap[dna[i]]++\n    }\n    var bases []byte\n    for k := range baseMap {\n        bases = append(bases, k)\n    }\n    sort.Slice(bases, func(i, j int) bool { \n        return bases[i] < bases[j]\n    })\n\n    fmt.Println(\"\\nBASE COUNT:\")\n    for _, base := range bases {\n        fmt.Printf(\"    %c: %3d\\n\", base, baseMap[base])\n    }\n    fmt.Println(\"    ------\")\n    fmt.Println(\"    Σ:\", le)\n    fmt.Println(\"    ======\\n\")\n}\n\n\nfunc wstring(w [3]int) string {\n    return fmt.Sprintf(\"  Change: %d\\n  Delete: %d\\n  Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    dna := generate(250)\n    prettyPrint(dna, 50)\n    muts := 10\n    w := [3]int{100, 100, 100} \n    fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n    fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n    for i := 0; i < muts; i++ {\n        dna = mutate(dna, w)\n    }\n    fmt.Println()\n    prettyPrint(dna, 50)\n}\n", "C": "#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\ntypedef struct genome{\n    char base;\n    struct genome *next;\n}genome;\n\ntypedef struct{\n    char mutation;\n    int position;\n}genomeChange;\n\ntypedef struct{\n    int adenineCount,thymineCount,cytosineCount,guanineCount;\n}baseCounts;\n\ngenome *strand;\nbaseCounts baseData;\nint genomeLength = 100, lineLength = 50;\n\nint numDigits(int num){\n    int len = 1;\n\n    while(num>10){\n        num /= 10;\n        len++;\n    }\n    return len;\n}\n\nvoid generateStrand(){\n\n    int baseChoice = rand()%4, i;\n    genome *strandIterator, *newStrand;\n\n    baseData.adenineCount = 0;\n    baseData.thymineCount = 0;\n    baseData.cytosineCount = 0;\n    baseData.guanineCount = 0;\n    \n    strand = (genome*)malloc(sizeof(genome));\n    strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n    baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n    strand->next = NULL;\n\n    strandIterator = strand;\n\n    for(i=1;i<genomeLength;i++){\n        baseChoice = rand()%4;\n\n        newStrand = (genome*)malloc(sizeof(genome));\n        newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n        baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n        newStrand->next = NULL;\n\n        strandIterator->next = newStrand;\n        strandIterator = newStrand;\n    }\n}\n\ngenomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){\n    int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);\n    \n    genomeChange mutationCommand;\n\n    mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');\n    mutationCommand.position = rand()%genomeLength;\n\n    return mutationCommand;\n}\n\nvoid printGenome(){\n    int rows, width = numDigits(genomeLength), len = 0,i,j;\n\tlineLength = (genomeLength<lineLength)?genomeLength:lineLength;\n\t\n\trows = genomeLength/lineLength + (genomeLength%lineLength!=0);\n\t\n    genome* strandIterator = strand;\n\n    printf(\"\\n\\nGenome : \\n--------\\n\");\n\n    for(i=0;i<rows;i++){\n        printf(\"\\n%*d%3s\",width,len,\":\");\n\n        for(j=0;j<lineLength && strandIterator!=NULL;j++){\n                printf(\"%c\",strandIterator->base);\n                strandIterator = strandIterator->next;\n        }\n        len += lineLength;\n    }\n\n    while(strandIterator!=NULL){\n            printf(\"%c\",strandIterator->base);\n            strandIterator = strandIterator->next;\n    }\n\n    printf(\"\\n\\nBase Counts\\n-----------\");\n\n    printf(\"\\n%*c%3s%*d\",width,'A',\":\",width,baseData.adenineCount);\n    printf(\"\\n%*c%3s%*d\",width,'T',\":\",width,baseData.thymineCount);\n    printf(\"\\n%*c%3s%*d\",width,'C',\":\",width,baseData.cytosineCount);\n    printf(\"\\n%*c%3s%*d\",width,'G',\":\",width,baseData.guanineCount);\n\t\n\tprintf(\"\\n\\nTotal:%*d\",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);\n\n    printf(\"\\n\");\n}\n\nvoid mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){\n    int i,j,width,baseChoice;\n    genomeChange newMutation;\n    genome *strandIterator, *strandFollower, *newStrand;\n\n    for(i=0;i<numMutations;i++){\n        strandIterator = strand;\n        strandFollower = strand;\n        newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);\n        width = numDigits(genomeLength);\n\n        for(j=0;j<newMutation.position;j++){\n            strandFollower = strandIterator;\n            strandIterator = strandIterator->next;\n        }\n            \n        if(newMutation.mutation=='S'){\n            if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='A'){\n                strandIterator->base='T';\n                printf(\"\\nSwapping A at position : %*d with T\",width,newMutation.position);\n            }\n            else if(strandIterator->base=='C'){\n                strandIterator->base='G';\n                printf(\"\\nSwapping C at position : %*d with G\",width,newMutation.position);\n            }\n            else{\n                strandIterator->base='C';\n                printf(\"\\nSwapping G at position : %*d with C\",width,newMutation.position);\n            }\n        }\n\n        else if(newMutation.mutation=='I'){\n            baseChoice = rand()%4;\n\n            newStrand = (genome*)malloc(sizeof(genome));\n            newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));\n            printf(\"\\nInserting %c at position : %*d\",newStrand->base,width,newMutation.position);\n            baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));\n            newStrand->next = strandIterator;\n            strandFollower->next = newStrand;\n            genomeLength++;\n        }\n\n        else{\n            strandFollower->next = strandIterator->next;\n            strandIterator->next = NULL;\n            printf(\"\\nDeleting %c at position : %*d\",strandIterator->base,width,newMutation.position);\n            free(strandIterator);\n            genomeLength--;\n        }\n    }\n}\n\nint main(int argc,char* argv[])\n{\n    int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;\n\n    if(argc==1||argc>6){\n                printf(\"Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\\n\",argv[0]);\n                return 0;\n    }\n\n    switch(argc){\n        case 2: genomeLength = atoi(argv[1]);\n                break;\n        case 3: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                break;\n        case 4: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                break;    \n        case 5: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                break; \n        case 6: genomeLength = atoi(argv[1]);\n                numMutations = atoi(argv[2]);\n                swapWeight   = atoi(argv[3]);\n                insertWeight = atoi(argv[4]);\n                deleteWeight = atoi(argv[5]);\n                break; \n    };\n\n    srand(time(NULL));\n    generateStrand();\n\t\n\tprintf(\"\\nOriginal:\");\n    printGenome();\n    mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);\n    \n\tprintf(\"\\n\\nMutated:\");\n\tprintGenome();\n\n    return 0;\n}\n"}
{"id": 45688, "name": "Tau number", "Go": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n    count := 0\n    i := 1\n    k := 2\n    if n%2 == 0 {\n        k = 1\n    }\n    for i*i <= n {\n        if n%i == 0 {\n            count++\n            j := n / i\n            if j != i {\n                count++\n            }\n        }\n        i += k\n    }\n    return count\n}\n\nfunc main() {\n    fmt.Println(\"The first 100 tau numbers are:\")\n    count := 0\n    i := 1\n    for count < 100 {\n        tf := countDivisors(i)\n        if i%tf == 0 {\n            fmt.Printf(\"%4d  \", i)\n            count++\n            if count%10 == 0 {\n                fmt.Println()\n            }\n        }\n        i++\n    }\n}\n", "C": "#include <stdio.h>\n\nunsigned int divisor_count(unsigned int n) {\n    unsigned int total = 1;\n    unsigned int p;\n\n    \n    for (; (n & 1) == 0; n >>= 1) {\n        ++total;\n    }\n    \n    for (p = 3; p * p <= n; p += 2) {\n        unsigned int count = 1;\n        for (; n % p == 0; n /= p) {\n            ++count;\n        }\n        total *= count;\n    }\n    \n    if (n > 1) {\n        total *= 2;\n    }\n    return total;\n}\n\nint main() {\n    const unsigned int limit = 100;\n    unsigned int count = 0;\n    unsigned int n;\n\n    printf(\"The first %d tau numbers are:\\n\", limit);\n    for (n = 1; count < limit; ++n) {\n        if (n % divisor_count(n) == 0) {\n            printf(\"%6d\", n);\n            ++count;\n            if (count % 10 == 0) {\n                printf(\"\\n\");\n            }\n        }\n    }\n\n    return 0;\n}\n"}
{"id": 45689, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n"}
{"id": 45690, "name": "Determinant and permanent", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += float64(s) * pr\n    }\n    return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n    p := make([]int, len(m))\n    for i := range p {\n        p[i] = i\n    }\n    it := permute.Iter(p)\n    for s := it(); s != 0; s = it() {\n        pr := 1.\n        for i, σ := range p {\n            pr *= m[i][σ]\n        }\n        d += pr\n    }\n    return\n}\n\nvar m2 = [][]float64{\n    {1, 2},\n    {3, 4}}\n\nvar m3 = [][]float64{\n    {2, 9, 4},\n    {7, 5, 3},\n    {6, 1, 8}}\n\nfunc main() {\n    fmt.Println(determinant(m2), permanent(m2))\n    fmt.Println(determinant(m3), permanent(m3))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ndouble det_in(double **in, int n, int perm)\n{\n\tif (n == 1) return in[0][0];\n\n\tdouble sum = 0, *m[--n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in[i + 1] + 1;\n\n\tfor (int i = 0, sgn = 1; i <= n; i++) {\n\t\tsum += sgn * (in[i][0] * det_in(m, n, perm));\n\t\tif (i == n) break;\n\n\t\tm[i] = in[i] + 1;\n\t\tif (!perm) sgn = -sgn;\n\t}\n\treturn sum;\n}\n\n\ndouble det(double *in, int n, int perm)\n{\n\tdouble *m[n];\n\tfor (int i = 0; i < n; i++)\n\t\tm[i] = in + (n * i);\n\n\treturn det_in(m, n, perm);\n}\n\nint main(void)\n{\n\tdouble x[] = {\t0, 1, 2, 3, 4,\n\t\t\t5, 6, 7, 8, 9,\n\t\t\t10, 11, 12, 13, 14,\n\t\t\t15, 16, 17, 18, 19,\n\t\t\t20, 21, 22, 23, 24 };\n\n\tprintf(\"det:  %14.12g\\n\", det(x, 5, 0));\n\tprintf(\"perm: %14.12g\\n\", det(x, 5, 1));\n\n\treturn 0;\n}\n"}
{"id": 45691, "name": "Partition function P", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n    \"time\"\n)\n\nvar p []*big.Int\nvar pd []int\n\nfunc partDiffDiff(n int) int {\n    if n&1 == 1 {\n        return (n + 1) / 2\n    }\n    return n + 1\n}\n\nfunc partDiff(n int) int {\n    if n < 2 {\n        return 1\n    }\n    pd[n] = pd[n-1] + partDiffDiff(n-1)\n    return pd[n]\n}\n\nfunc partitionsP(n int) {\n    if n < 2 {\n        return\n    }\n    psum := new(big.Int)\n    for i := 1; i <= n; i++ {\n        pdi := partDiff(i)\n        if pdi > n {\n            break\n        }\n        sign := int64(-1)\n        if (i-1)%4 < 2 {\n            sign = 1\n        }\n        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))\n        psum.Add(psum, t)\n    }\n    p[n] = psum\n}\n\nfunc main() {\n    start := time.Now()\n    const N = 6666\n    p = make([]*big.Int, N+1)\n    pd = make([]int, N+1)\n    p[0], pd[0] = big.NewInt(1), 1\n    p[1], pd[1] = big.NewInt(1), 1\n    for n := 2; n <= N; n++ {\n        partitionsP(n)\n    }\n    fmt.Printf(\"p[%d)] = %d\\n\", N, p[N])\n    fmt.Printf(\"Took %s\\n\", time.Since(start))\n}\n", "C": "#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <gmp.h>\n\nmpz_t* partition(uint64_t n) {\n\tmpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));\n\tmpz_init_set_ui(pn[0], 1);\n\tmpz_init_set_ui(pn[1], 1);\n\tfor (uint64_t i = 2; i < n + 2; i ++) {\n\t\tmpz_init(pn[i]);\n\t\tfor (uint64_t k = 1, penta; ; k++) {\n\t\t\tpenta = k * (3 * k - 1) >> 1;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t\tpenta += k;\n\t\t\tif (penta >= i) break;\n\t\t\tif (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);\n\t\t\telse mpz_sub(pn[i], pn[i], pn[i - penta]);\n\t\t}\n\t}\n\tmpz_t *tmp = &pn[n + 1];\n\tfor (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);\n\tfree(pn);\n\treturn tmp;\n}\n\nint main(int argc, char const *argv[]) {\n\tclock_t start = clock();\n\tmpz_t *p = partition(6666);\n\tgmp_printf(\"%Zd\\n\", p);\n\tprintf(\"Elapsed time: %.04f seconds\\n\",\n\t\t(double)(clock() - start) / (double)CLOCKS_PER_SEC);\n\treturn 0;\n}\n"}
{"id": 45692, "name": "Wireworld", "Go": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io/ioutil\"\n    \"strings\"\n)\n\nvar rows, cols int \nvar rx, cx int     \nvar mn []int       \n\nfunc main() {\n    \n    src, err := ioutil.ReadFile(\"ww.config\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    srcRows := bytes.Split(src, []byte{'\\n'})\n\n    \n    rows = len(srcRows)\n    for _, r := range srcRows {\n        if len(r) > cols {\n            cols = len(r)\n        }\n    }\n    rx, cx = rows+2, cols+2\n    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n    \n    odd := make([]byte, rx*cx)\n    even := make([]byte, rx*cx)\n    for ri, r := range srcRows {\n        copy(odd[(ri+1)*cx+1:], r)\n    }\n\n    \n    for {\n        print(odd)\n        step(even, odd)\n        fmt.Scanln()\n\n        print(even)\n        step(odd, even)\n        fmt.Scanln()\n    }\n}\n\nfunc print(grid []byte) {\n    fmt.Println(strings.Repeat(\"__\", cols))\n    fmt.Println()\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            if grid[r*cx+c] == 0 {\n                fmt.Print(\"  \")\n            } else {\n                fmt.Printf(\" %c\", grid[r*cx+c])\n            }\n        }\n        fmt.Println()\n    }\n}\n\nfunc step(dst, src []byte) {\n    for r := 1; r <= rows; r++ {\n        for c := 1; c <= cols; c++ {\n            x := r*cx + c\n            dst[x] = src[x]\n            switch dst[x] {\n            case 'H':\n                dst[x] = 't'\n            case 't':\n                dst[x] = '.'\n            case '.':\n                var nn int\n                for _, n := range mn {\n                    if src[x+n] == 'H' {\n                        nn++\n                    }\n                }\n                if nn == 1 || nn == 2 {\n                    dst[x] = 'H'\n                }\n            }\n        }\n    }\n}\n", "C": "\n#define ANIMATE_VT100_POSIX\n#include <stdio.h>\n#include <string.h>\n#ifdef ANIMATE_VT100_POSIX\n#include <time.h>\n#endif\n\nchar world_7x14[2][512] = {\n  {\n    \"+-----------+\\n\"\n    \"|tH.........|\\n\"\n    \"|.   .      |\\n\"\n    \"|   ...     |\\n\"\n    \"|.   .      |\\n\"\n    \"|Ht.. ......|\\n\"\n    \"+-----------+\\n\"\n  }\n};\n\nvoid next_world(const char *in, char *out, int w, int h)\n{\n  int i;\n\n  for (i = 0; i < w*h; i++) {\n    switch (in[i]) {\n    case ' ': out[i] = ' '; break;\n    case 't': out[i] = '.'; break;\n    case 'H': out[i] = 't'; break;\n    case '.': {\n      int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') +\n               (in[i-1]   == 'H')                    + (in[i+1]   == 'H') +\n               (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H');\n      out[i] = (hc == 1 || hc == 2) ? 'H' : '.';\n      break;\n    }\n    default:\n      out[i] = in[i];\n    }\n  }\n  out[i] = in[i];\n}\n\nint main()\n{\n  int f;\n\n  for (f = 0; ; f = 1 - f) {\n    puts(world_7x14[f]);\n    next_world(world_7x14[f], world_7x14[1-f], 14, 7);\n#ifdef ANIMATE_VT100_POSIX\n    printf(\"\\x1b[%dA\", 8);\n    printf(\"\\x1b[%dD\", 14);\n    {\n      static const struct timespec ts = { 0, 100000000 };\n      nanosleep(&ts, 0);\n    }\n#endif\n  }\n\n  return 0;\n}\n"}
{"id": 45693, "name": "Ray-casting algorithm", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\ntype seg struct {\n    p1, p2 xy\n}\n\ntype poly struct {\n    name  string\n    sides []seg\n}\n\nfunc inside(pt xy, pg poly) (i bool) {\n    for _, side := range pg.sides {\n        if rayIntersectsSegment(pt, side) {\n            i = !i\n        }\n    }\n    return\n}\n\nfunc rayIntersectsSegment(p xy, s seg) bool {\n    var a, b xy\n    if s.p1.y < s.p2.y {\n        a, b = s.p1, s.p2\n    } else {\n        a, b = s.p2, s.p1\n    }\n    for p.y == a.y || p.y == b.y {\n        p.y = math.Nextafter(p.y, math.Inf(1))\n    }\n    if p.y < a.y || p.y > b.y {\n        return false\n    }\n    if a.x > b.x {\n        if p.x > a.x {\n            return false\n        }\n        if p.x < b.x {\n            return true\n        }\n    } else {\n        if p.x > b.x {\n            return false\n        }\n        if p.x < a.x {\n            return true\n        }\n    }\n    return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)\n}\n\nvar (\n    p1  = xy{0, 0}\n    p2  = xy{10, 0}\n    p3  = xy{10, 10}\n    p4  = xy{0, 10}\n    p5  = xy{2.5, 2.5}\n    p6  = xy{7.5, 2.5}\n    p7  = xy{7.5, 7.5}\n    p8  = xy{2.5, 7.5}\n    p9  = xy{0, 5}\n    p10 = xy{10, 5}\n    p11 = xy{3, 0}\n    p12 = xy{7, 0}\n    p13 = xy{7, 10}\n    p14 = xy{3, 10}\n)\n\nvar tpg = []poly{\n    {\"square\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},\n    {\"square hole\", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},\n        {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},\n    {\"strange\", []seg{{p1, p5},\n        {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},\n    {\"exagon\", []seg{{p11, p12}, {p12, p10}, {p10, p13},\n        {p13, p14}, {p14, p9}, {p9, p11}}},\n}\n\nvar tpt = []xy{\n    \n    {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},\n    \n    {1, 2}, {2, 1},\n}\n\nfunc main() {\n    for _, pg := range tpg {\n        fmt.Printf(\"%s:\\n\", pg.name)\n        for _, pt := range tpt {\n            fmt.Println(pt, inside(pt, pg))\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec;\ntypedef struct { int n; vec* v; } polygon_t, *polygon;\n\n#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}\n#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }\nBIN_V(sub, a.x - b.x, a.y - b.y);\nBIN_V(add, a.x + b.x, a.y + b.y);\nBIN_S(dot, a.x * b.x + a.y * b.y);\nBIN_S(cross, a.x * b.y - a.y * b.x);\n\n\nvec vmadd(vec a, double s, vec b)\n{\n\tvec c;\n\tc.x = a.x + s * b.x;\n\tc.y = a.y + s * b.y;\n\treturn c;\n}\n\n\nint intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)\n{\n\tvec dx = vsub(x1, x0), dy = vsub(y1, y0);\n\tdouble d = vcross(dy, dx), a;\n\tif (!d) return 0; \n\n\ta = (vcross(x0, dx) - vcross(y0, dx)) / d;\n\tif (sect)\n\t\t*sect = vmadd(y0, a, dy);\n\n\tif (a < -tol || a > 1 + tol) return -1;\n\tif (a < tol || a > 1 - tol) return 0;\n\n\ta = (vcross(x0, dy) - vcross(y0, dy)) / d;\n\tif (a < 0 || a > 1) return -1;\n\n\treturn 1;\n}\n\n\ndouble dist(vec x, vec y0, vec y1, double tol)\n{\n\tvec dy = vsub(y1, y0);\n\tvec x1, s;\n\tint r;\n\n\tx1.x = x.x + dy.y; x1.y = x.y - dy.x;\n\tr = intersect(x, x1, y0, y1, tol, &s);\n\tif (r == -1) return HUGE_VAL;\n\ts = vsub(s, x);\n\treturn sqrt(vdot(s, s));\n}\n\n#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)\n\nint inside(vec v, polygon p, double tol)\n{\n\t\n\tint i, k, crosses, intersectResult;\n\tvec *pv;\n\tdouble min_x, max_x, min_y, max_y;\n\n\tfor (i = 0; i < p->n; i++) {\n\t\tk = (i + 1) % p->n;\n\t\tmin_x = dist(v, p->v[i], p->v[k], tol);\n\t\tif (min_x < tol) return 0;\n\t}\n\n\tmin_x = max_x = p->v[0].x;\n\tmin_y = max_y = p->v[1].y;\n\n\t\n\tfor_v(i, pv, p) {\n\t\tif (pv->x > max_x) max_x = pv->x;\n\t\tif (pv->x < min_x) min_x = pv->x;\n\t\tif (pv->y > max_y) max_y = pv->y;\n\t\tif (pv->y < min_y) min_y = pv->y;\n\t}\n\tif (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)\n\t\treturn -1;\n\n\tmax_x -= min_x; max_x *= 2;\n\tmax_y -= min_y; max_y *= 2;\n\tmax_x += max_y;\n\n\tvec e;\n\twhile (1) {\n\t\tcrosses = 0;\n\t\t\n\t\te.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\t\te.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;\n\n\t\tfor (i = 0; i < p->n; i++) {\n\t\t\tk = (i + 1) % p->n;\n\t\t\tintersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);\n\n\t\t\t\n\t\t\tif (!intersectResult) break;\n\n\t\t\tif (intersectResult == 1) crosses++;\n\t\t}\n\t\tif (i == p->n) break;\n\t}\n\treturn (crosses & 1) ? 1 : -1;\n}\n\nint main()\n{\n\tvec vsq[] = {\t{0,0}, {10,0}, {10,10}, {0,10},\n\t\t\t{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};\n\n\tpolygon_t sq = { 4, vsq }, \n\t\tsq_hole = { 8, vsq }; \n\n\tvec c = { 10, 5 }; \n\tvec d = { 5, 5 };\n\n\tprintf(\"%d\\n\", inside(c, &sq, 1e-10));\n\tprintf(\"%d\\n\", inside(c, &sq_hole, 1e-10));\n\n\tprintf(\"%d\\n\", inside(d, &sq, 1e-10));\t\n\tprintf(\"%d\\n\", inside(d, &sq_hole, 1e-10));  \n\n\treturn 0;\n}\n"}
{"id": 45694, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n"}
{"id": 45695, "name": "Elliptic curve arithmetic", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n    return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n    return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n    return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n    if is_zero(p) {\n        return p\n    }\n    L := (3 * p.x * p.x) / (2 * p.y)\n    x := L*L - 2*p.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc add(p, q pt) pt {\n    if p.x == q.x && p.y == q.y {\n        return dbl(p)\n    }\n    if is_zero(p) {\n        return q\n    }\n    if is_zero(q) {\n        return p\n    }\n    L := (q.y - p.y) / (q.x - p.x)\n    x := L*L - p.x - q.x\n    return pt{\n        x: x,\n        y: L*(p.x-x) - p.y,\n    }\n}\n\nfunc mul(p pt, n int) pt {\n    r := zero()\n    for i := 1; i <= n; i <<= 1 {\n        if i&n != 0 {\n            r = add(r, p)\n        }\n        p = dbl(p)\n    }\n    return r\n}\n\nfunc show(s string, p pt) {\n    fmt.Printf(\"%s\", s)\n    if is_zero(p) {\n        fmt.Println(\"Zero\")\n    } else {\n        fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n    }\n}\n\nfunc from_y(y float64) pt {\n    return pt{\n        x: math.Cbrt(y*y - bCoeff),\n        y: y,\n    }\n}\n    \nfunc main() {\n    a := from_y(1)\n    b := from_y(2)\n    show(\"a = \", a)\n    show(\"b = \", b)\n    c := add(a, b)\n    show(\"c = a + b = \", c)\n    d := neg(c)\n    show(\"d = -c = \", d)\n    show(\"c + d = \", add(c, d))\n    show(\"a + b + d = \", add(a, add(b, d)))\n    show(\"a * 12345 = \", mul(a, 12345))\n}\n", "C": "#include <stdio.h>\n#include <math.h>\n\n#define C 7\ntypedef struct { double x, y; } pt;\n\npt zero(void) { return (pt){ INFINITY, INFINITY }; }\n\n\nint is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }\n\npt neg(pt p) { return (pt){ p.x, -p.y }; }\n\npt dbl(pt p) {\n\tif (is_zero(p)) return p;\n\n\tpt r;\n\tdouble L = (3 * p.x * p.x) / (2 * p.y);\n\tr.x = L * L - 2 * p.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt add(pt p, pt q) {\n\tif (p.x == q.x && p.y == q.y) return dbl(p);\n\tif (is_zero(p)) return q;\n\tif (is_zero(q)) return p;\n\n\tpt r;\n\tdouble L = (q.y - p.y) / (q.x - p.x);\n\tr.x = L * L - p.x - q.x;\n\tr.y = L * (p.x - r.x) - p.y;\n\treturn r;\n}\n\npt mul(pt p, int n) {\n\tint i;\n\tpt r = zero();\n\n\tfor (i = 1; i <= n; i <<= 1) {\n\t\tif (i & n) r = add(r, p);\n\t\tp = dbl(p);\n\t}\n\treturn r;\n}\n\nvoid show(const char *s, pt p) {\n\tprintf(\"%s\", s);\n\tprintf(is_zero(p) ? \"Zero\\n\" : \"(%.3f, %.3f)\\n\", p.x, p.y);\n}\n\npt from_y(double y) {\n\tpt r;\n\tr.x = pow(y * y - C, 1.0/3);\n\tr.y = y;\n\treturn r;\n}\n\nint main(void) {\n\tpt a, b, c, d;\n\n\ta = from_y(1);\n\tb = from_y(2);\n\n\tshow(\"a = \", a);\n\tshow(\"b = \", b);\n\tshow(\"c = a + b = \", c = add(a, b));\n\tshow(\"d = -c = \", d = neg(c));\n\tshow(\"c + d = \", add(c, d));\n\tshow(\"a + b + d = \", add(a, add(b, d)));\n\tshow(\"a * 12345 = \", mul(a, 12345));\n\n\treturn 0;\n}\n"}
{"id": 45696, "name": "Count occurrences of a substring", "Go": "package main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \n}\n", "C": "#include <stdio.h>\n#include <string.h>\n\nint match(const char *s, const char *p, int overlap)\n{\n        int c = 0, l = strlen(p);\n\n        while (*s != '\\0') {\n                if (strncmp(s++, p, l)) continue;\n                if (!overlap) s += l - 1;\n                c++;\n        }\n        return c;\n}\n\nint main()\n{\n        printf(\"%d\\n\", match(\"the three truths\", \"th\", 0));\n        printf(\"overlap:%d\\n\", match(\"abababababa\", \"aba\", 1));\n        printf(\"not:    %d\\n\", match(\"abababababa\", \"aba\", 0));\n        return 0;\n}\n"}
{"id": 45697, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 45698, "name": "Numbers with prime digits whose sum is 13", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"strconv\"\n)\n\nfunc combrep(n int, lst []byte) [][]byte {\n    if n == 0 {\n        return [][]byte{nil}\n    }\n    if len(lst) == 0 {\n        return nil\n    }\n    r := combrep(n, lst[1:])\n    for _, x := range combrep(n-1, lst) {\n        r = append(r, append(x, lst[0]))\n    }\n    return r\n}\n\nfunc shouldSwap(s []byte, start, curr int) bool {\n    for i := start; i < curr; i++ {\n        if s[i] == s[curr] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc findPerms(s []byte, index, n int, res *[]string) {\n    if index >= n {\n        *res = append(*res, string(s))\n        return\n    }\n    for i := index; i < n; i++ {\n        check := shouldSwap(s, index, i)\n        if check {\n            s[index], s[i] = s[i], s[index]\n            findPerms(s, index+1, n, res)\n            s[index], s[i] = s[i], s[index]\n        }\n    }\n}\n\nfunc main() {\n    primes := []byte{2, 3, 5, 7}\n    var res []string\n    for n := 3; n <= 6; n++ {\n        reps := combrep(n, primes)\n        for _, rep := range reps {\n            sum := byte(0)\n            for _, r := range rep {\n                sum += r\n            }\n            if sum == 13 {\n                var perms []string\n                for i := 0; i < len(rep); i++ {\n                    rep[i] += 48\n                }\n                findPerms(rep, 0, len(rep), &perms)\n                res = append(res, perms...)\n            }\n        }\n    }\n    res2 := make([]int, len(res))\n    for i, r := range res {\n        res2[i], _ = strconv.Atoi(r)\n    }\n    sort.Ints(res2)\n    fmt.Println(\"Those numbers whose digits are all prime and sum to 13 are:\")\n    fmt.Println(res2)\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n\nbool primeDigitsSum13(int n) {\n    int sum = 0;\n    while (n > 0) {\n        int r = n % 10;\n        switch (r) {\n        case 2:\n        case 3:\n        case 5:\n        case 7:\n            break;\n        default:\n            return false;\n        }\n        n /= 10;\n        sum += r;\n    }\n    return sum == 13;\n}\n\nint main() {\n    int i, c;\n\n    \n    c = 0;\n    for (i = 1; i < 1000000; i++) {\n        if (primeDigitsSum13(i)) {\n            printf(\"%6d \", i);\n            if (c++ == 10) {\n                c = 0;\n                printf(\"\\n\");\n            }\n        }\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n"}
{"id": 45699, "name": "String comparison", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \n    c := \"cat\"\n    d := \"dog\"\n    if c == d {\n        fmt.Println(c, \"is bytewise identical to\", d)\n    }\n    if c != d {\n        fmt.Println(c, \"is bytewise different from\", d)\n    }\n    if c > d {\n        fmt.Println(c, \"is lexically bytewise greater than\", d)\n    }\n    if c < d {\n        fmt.Println(c, \"is lexically bytewise less than\", d)\n    }\n    if c >= d {\n        fmt.Println(c, \"is lexically bytewise greater than or equal to\", d)\n    }\n    if c <= d {\n        fmt.Println(c, \"is lexically bytewise less than or equal to\", d)\n    }\n    \n    \n\n    \n    \n    eqf := `when interpreted as UTF-8 and compared under Unicode\nsimple case folding rules.`\n    if strings.EqualFold(c, d) {\n        fmt.Println(c, \"equal to\", d, eqf)\n    } else {\n        fmt.Println(c, \"not equal to\", d, eqf)\n    }\n\n    \n    \n    \n    \n    \n    \n    \n}\n", "C": "\nif (strcmp(a,b)) action_on_equality();\n"}
{"id": 45700, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n"}
{"id": 45701, "name": "Take notes on the command line", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc addNote(fn string, note string) error {\n\tf, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), \"\\n\\t\", note, \"\\n\")\n\t\n\tif cErr := f.Close(); err == nil {\n\t\terr = cErr\n\t}\n\treturn err\n}\n\nfunc showNotes(w io.Writer, fn string) error {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \n\t\t}\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, f)\n\tf.Close()\n\treturn err\n}\n\nfunc main() {\n\tconst fn = \"NOTES.TXT\"\n\tvar err error\n\tif len(os.Args) > 1 {\n\t\terr = addNote(fn, strings.Join(os.Args[1:], \" \"))\n\t} else {\n\t\terr = showNotes(os.Stdout, fn)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n", "C": "#include <stdio.h>\n#include <time.h>\n\n#define note_file \"NOTES.TXT\"\n\nint main(int argc, char**argv)\n{\n\tFILE *note = 0;\n\ttime_t tm;\n\tint i;\n\tchar *p;\n\n\tif (argc < 2) {\n\t\tif ((note = fopen(note_file, \"r\")))\n\t\t\twhile ((i = fgetc(note)) != EOF)\n\t\t\t\tputchar(i);\n\n\t} else if ((note = fopen(note_file, \"a\"))) {\n\t\ttm = time(0);\n\t\tp = ctime(&tm);\n\n\t\t\n\t\twhile (*p) fputc(*p != '\\n'?*p:'\\t', note), p++;\n\n\t\tfor (i = 1; i < argc; i++)\n\t\t\tfprintf(note, \"%s%c\", argv[i], 1 + i - argc ? ' ' : '\\n');\n\t}\n\n\tif (note) fclose(note);\n\treturn 0;\n}\n"}
{"id": 45702, "name": "Thiele's interpolation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define N 32\n#define N2 (N * (N - 1) / 2)\n#define STEP .05\n\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\n\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\n\n\n\ndouble rho(double *x, double *y, double *r, int i, int n)\n{\n\tif (n < 0) return 0;\n\tif (!n) return y[i];\n\n\tint idx = (N - 1 - n) * (N - n) / 2 + i;\n\tif (r[idx] != r[idx]) \n\t\tr[idx] = (x[i] - x[i + n])\n\t\t\t/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n\t\t\t+ rho(x, y, r, i + 1, n - 2);\n\treturn r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, int n)\n{\n\tif (n > N - 1) return 1;\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n\t\t+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\n#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)\n#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)\n#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\txval[i] = i * STEP;\n\t\tt_sin[i] = sin(xval[i]);\n\t\tt_cos[i] = cos(xval[i]);\n\t\tt_tan[i] = t_sin[i] / t_cos[i];\n\t}\n\tfor (i = 0; i < N2; i++)\n\t\t\n\t\tr_sin[i] = r_cos[i] = r_tan[i] = 0/0.;\n\n\tprintf(\"%16.14f\\n\", 6 * i_sin(.5));\n\tprintf(\"%16.14f\\n\", 3 * i_cos(.5));\n\tprintf(\"%16.14f\\n\", 4 * i_tan(1.));\n\treturn 0;\n}\n"}
{"id": 45703, "name": "Thiele's interpolation formula", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    \n    const nn = 32\n    const step = .05\n    xVal := make([]float64, nn)\n    tSin := make([]float64, nn)\n    tCos := make([]float64, nn)\n    tTan := make([]float64, nn)\n    for i := range xVal {\n        xVal[i] = float64(i) * step\n        tSin[i], tCos[i] = math.Sincos(xVal[i])\n        tTan[i] = tSin[i] / tCos[i]\n    }\n    \n    iSin := thieleInterpolator(tSin, xVal)\n    iCos := thieleInterpolator(tCos, xVal)\n    iTan := thieleInterpolator(tTan, xVal)\n    \n    fmt.Printf(\"%16.14f\\n\", 6*iSin(.5))\n    fmt.Printf(\"%16.14f\\n\", 3*iCos(.5))\n    fmt.Printf(\"%16.14f\\n\", 4*iTan(1))\n}\n\nfunc thieleInterpolator(x, y []float64) func(float64) float64 {\n    n := len(x)\n    ρ := make([][]float64, n)\n    for i := range ρ {\n        ρ[i] = make([]float64, n-i)\n        ρ[i][0] = y[i]\n    }\n    for i := 0; i < n-1; i++ {\n        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])\n    }\n    for i := 2; i < n; i++ {\n        for j := 0; j < n-i; j++ {\n            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]\n        }\n    }\n    \n    ρ0 := ρ[0]\n    return func(xin float64) float64 {\n        var a float64\n        for i := n - 1; i > 1; i-- {\n            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)\n        }\n        return y[0] + (xin-x[0])/(ρ0[1]+a)\n    }\n}\n", "C": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define N 32\n#define N2 (N * (N - 1) / 2)\n#define STEP .05\n\ndouble xval[N], t_sin[N], t_cos[N], t_tan[N];\n\n\ndouble r_sin[N2], r_cos[N2], r_tan[N2];\n\n\n\n\ndouble rho(double *x, double *y, double *r, int i, int n)\n{\n\tif (n < 0) return 0;\n\tif (!n) return y[i];\n\n\tint idx = (N - 1 - n) * (N - n) / 2 + i;\n\tif (r[idx] != r[idx]) \n\t\tr[idx] = (x[i] - x[i + n])\n\t\t\t/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))\n\t\t\t+ rho(x, y, r, i + 1, n - 2);\n\treturn r[idx];\n}\n\ndouble thiele(double *x, double *y, double *r, double xin, int n)\n{\n\tif (n > N - 1) return 1;\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)\n\t\t+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);\n}\n\n#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)\n#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)\n#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)\n\nint main()\n{\n\tint i;\n\tfor (i = 0; i < N; i++) {\n\t\txval[i] = i * STEP;\n\t\tt_sin[i] = sin(xval[i]);\n\t\tt_cos[i] = cos(xval[i]);\n\t\tt_tan[i] = t_sin[i] / t_cos[i];\n\t}\n\tfor (i = 0; i < N2; i++)\n\t\t\n\t\tr_sin[i] = r_cos[i] = r_tan[i] = 0/0.;\n\n\tprintf(\"%16.14f\\n\", 6 * i_sin(.5));\n\tprintf(\"%16.14f\\n\", 3 * i_cos(.5));\n\tprintf(\"%16.14f\\n\", 4 * i_tan(1.));\n\treturn 0;\n}\n"}
{"id": 45704, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n"}
{"id": 45705, "name": "Fibonacci word", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s  %-18s  %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d  %.16f  %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d  %.16f\\n\", n, len(s), entropy(s))\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nvoid print_headings()\n{\n\tprintf(\"%2s\", \"N\");\n\tprintf(\" %10s\", \"Length\");\n\tprintf(\" %-20s\", \"Entropy\");\n\tprintf(\" %-40s\", \"Word\");\n\tprintf(\"\\n\");\n}\n\ndouble calculate_entropy(int ones, int zeros)\n{\n\tdouble result = 0;\n\t\n\tint total = ones + zeros;\n\tresult -= (double) ones / total * log2((double) ones / total);\n\tresult -= (double) zeros / total * log2((double) zeros / total);\n\t\n\tif (result != result) { \n\t\tresult = 0;\n\t}\n\t\n\treturn result;\n}\n\nvoid print_entropy(char *word)\n{\n\tint ones = 0;\n\tint zeros = 0;\n\t\n\tint i;\n\tfor (i = 0; word[i]; i++) {\n\t\tchar c = word[i];\n\t\t\n\t\tswitch (c) {\n\t\t\tcase '0':\n\t\t\t\tzeros++;\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tones++;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tdouble entropy = calculate_entropy(ones, zeros);\n\tprintf(\" %-20.18f\", entropy);\n}\n\nvoid print_word(int n, char *word)\n{\n\tprintf(\"%2d\", n);\n\t\n\tprintf(\" %10ld\", strlen(word));\n\t\n\tprint_entropy(word);\n\t\n\tif (n < 10) {\n\t\tprintf(\" %-40s\", word);\n\t} else {\n\t\tprintf(\" %-40s\", \"...\");\n\t}\n\t\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tprint_headings();\n\t\n\tchar *last_word = malloc(2);\n\tstrcpy(last_word, \"1\");\n\t\n\tchar *current_word = malloc(2);\n\tstrcpy(current_word, \"0\");\n\t\n\tprint_word(1, last_word);\n\tint i;\n\tfor (i = 2; i <= 37; i++) {\n\t\tprint_word(i, current_word);\n\t\t\n\t\tchar *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);\n\t\tstrcpy(next_word, current_word);\n\t\tstrcat(next_word, last_word);\n\t\t\n\t\tfree(last_word);\n\t\tlast_word = current_word;\n\t\tcurrent_word = next_word;\n\t}\n\t\n\tfree(last_word);\n\tfree(current_word);\n\treturn 0;\n}\n"}
{"id": 45706, "name": "Angles (geometric), normalization and conversion", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"strconv\"\n    \"strings\"\n)\n\nfunc d2d(d float64) float64 { return math.Mod(d, 360) }\n\nfunc g2g(g float64) float64 { return math.Mod(g, 400) }\n\nfunc m2m(m float64) float64 { return math.Mod(m, 6400) }\n\nfunc r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }\n\nfunc d2g(d float64) float64 { return d2d(d) * 400 / 360 }\n\nfunc d2m(d float64) float64 { return d2d(d) * 6400 / 360 }\n\nfunc d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }\n\nfunc g2d(g float64) float64 { return g2g(g) * 360 / 400 }\n\nfunc g2m(g float64) float64 { return g2g(g) * 6400 / 400 }\n\nfunc g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }\n\nfunc m2d(m float64) float64 { return m2m(m) * 360 / 6400 }\n\nfunc m2g(m float64) float64 { return m2m(m) * 400 / 6400 }\n\nfunc m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }\n\nfunc r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }\n\nfunc r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }\n\nfunc r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }\n\n\nfunc s(f float64) string {\n    wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), \".\")\n    if len(wf) == 1 {\n        return fmt.Sprintf(\"%7s        \", wf[0])\n    }\n    le := len(wf[1])\n    if le > 7 {\n        le = 7\n    }\n    return fmt.Sprintf(\"%7s.%-7s\", wf[0], wf[1][:le])\n}\n\nfunc main() {\n    angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,\n        359, 399, 6399, 1000000}\n    ft := \"%s %s %s %s %s\\n\"\n    fmt.Printf(ft, \"    degrees    \", \"normalized degs\", \"    gradians   \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))\n    }\n    fmt.Printf(ft, \"\\n   gradians    \", \"normalized grds\", \"    degrees    \", \"     mils      \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))\n    }\n    fmt.Printf(ft, \"\\n     mils      \", \"normalized mils\", \"    degrees    \", \"   gradians    \", \"     radians\")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))\n    }\n    fmt.Printf(ft, \"\\n    radians    \", \"normalized rads\", \"    degrees    \", \"   gradians    \", \"      mils  \")\n    for _, a := range angles {\n        fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))\n    }\n}\n", "C": "#define PI 3.141592653589793\n#define TWO_PI 6.283185307179586\n\ndouble normalize2deg(double a) {\n  while (a < 0) a += 360;\n  while (a >= 360) a -= 360;\n  return a;\n}\ndouble normalize2grad(double a) {\n  while (a < 0) a += 400;\n  while (a >= 400) a -= 400;\n  return a;\n}\ndouble normalize2mil(double a) {\n  while (a < 0) a += 6400;\n  while (a >= 6400) a -= 6400;\n  return a;\n}\ndouble normalize2rad(double a) {\n  while (a < 0) a += TWO_PI;\n  while (a >= TWO_PI) a -= TWO_PI;\n  return a;\n}\n\ndouble deg2grad(double a) {return a * 10 / 9;}\ndouble deg2mil(double a) {return a * 160 / 9;}\ndouble deg2rad(double a) {return a * PI / 180;}\n\ndouble grad2deg(double a) {return a * 9 / 10;}\ndouble grad2mil(double a) {return a * 16;}\ndouble grad2rad(double a) {return a * PI / 200;}\n\ndouble mil2deg(double a) {return a * 9 / 160;}\ndouble mil2grad(double a) {return a / 16;}\ndouble mil2rad(double a) {return a * PI / 3200;}\n\ndouble rad2deg(double a) {return a * 180 / PI;}\ndouble rad2grad(double a) {return a * 200 / PI;}\ndouble rad2mil(double a) {return a * 3200 / PI;}\n"}
{"id": 45707, "name": "Find common directory path", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tc := []byte(path.Clean(paths[0]))\n\n\t\n\t\n\t\n\t\n\t\n\t\n\tc = append(c, sep)\n\n\t\n\tfor _, v := range paths[1:] {\n\t\t\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t\t\"/home\n\t\t\"/home/user1/././tmp/covertly/foo\",\n\t\t\"/home/bob/../user1/tmp/coved/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n", "C": "#include <stdio.h>\n\nint common_len(const char *const *names, int n, char sep)\n{\n\tint i, pos;\n\tfor (pos = 0; ; pos++) {\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tif (names[i][pos] != '\\0' &&\n\t\t\t\t\tnames[i][pos] == names[0][pos])\n\t\t\t\tcontinue;\n\n\t\t\t\n\t\t\twhile (pos > 0 && names[0][--pos] != sep);\n\t\t\treturn pos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint main()\n{\n\tconst char *names[] = {\n\t\t\"/home/user1/tmp/coverage/test\",\n\t\t\"/home/user1/tmp/covert/operator\",\n\t\t\"/home/user1/tmp/coven/members\",\n\t};\n\tint len = common_len(names, sizeof(names) / sizeof(const char*), '/');\n\n\tif (!len) printf(\"No common path\\n\");\n\telse      printf(\"Common path: %.*s\\n\", len, names[0]);\n\n\treturn 0;\n}\n"}
{"id": 45708, "name": "Verify distribution uniformity_Naive", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\ninline int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n\ninline int rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\n\nint check(int (*gen)(), int n, int cnt, double delta) \n{\n\tint i = cnt, *bins = calloc(sizeof(int), n);\n\tdouble ratio;\n\twhile (i--) bins[gen() - 1]++;\n\tfor (i = 0; i < n; i++) {\n\t\tratio = bins[i] * n / (double)cnt - 1;\n\t\tif (ratio > -delta && ratio < delta) continue;\n\n\t\tprintf(\"bin %d out of range: %d (%g%% vs %g%%), \",\n\t\t\ti + 1, bins[i], ratio * 100, delta * 100);\n\t\tbreak;\n\t}\n\tfree(bins);\n\treturn i == n;\n}\n\nint main()\n{\n\tint cnt = 1;\n\twhile ((cnt *= 10) <= 1000000) {\n\t\tprintf(\"Count = %d: \", cnt);\n\t\tprintf(check(rand5_7, 7, cnt, 0.03) ? \"flat\\n\" : \"NOT flat\\n\");\n\t}\n\n\treturn 0;\n}\n"}
{"id": 45709, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n"}
{"id": 45710, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n"}
{"id": 45711, "name": "Stirling numbers of the second kind", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nfunc main() {\n    limit := 100\n    last := 12\n    s2 := make([][]*big.Int, limit+1)\n    for n := 0; n <= limit; n++ {\n        s2[n] = make([]*big.Int, limit+1)\n        for k := 0; k <= limit; k++ {\n            s2[n][k] = new(big.Int)\n        }\n        s2[n][n].SetInt64(int64(1))\n    }\n    var t big.Int\n    for n := 1; n <= limit; n++ {\n        for k := 1; k <= n; k++ {\n            t.SetInt64(int64(k))\n            t.Mul(&t, s2[n-1][k])\n            s2[n][k].Add(&t, s2[n-1][k-1])\n        }\n    }\n    fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n    fmt.Printf(\"n/k\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"%9d \", i)\n    }\n    fmt.Printf(\"\\n--\")\n    for i := 0; i <= last; i++ {\n        fmt.Printf(\"----------\")\n    }\n    fmt.Println()\n    for n := 0; n <= last; n++ {\n        fmt.Printf(\"%2d \", n)\n        for k := 0; k <= n; k++ {\n            fmt.Printf(\"%9d \", s2[n][k])\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n    max := new(big.Int).Set(s2[limit][0])\n    for k := 1; k <= limit; k++ {\n        if s2[limit][k].Cmp(max) > 0 {\n            max.Set(s2[limit][k])\n        }\n    }\n    fmt.Println(max)\n    fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stirling_cache_tag {\n    int max;\n    int* values;\n} stirling_cache;\n\nint stirling_number2(stirling_cache* sc, int n, int k) {\n    if (k == n)\n        return 1;\n    if (k == 0 || k > n || n > sc->max)\n        return 0;\n    return sc->values[n*(n-1)/2 + k - 1];\n}\n\nbool stirling_cache_create(stirling_cache* sc, int max) {\n    int* values = calloc(max * (max + 1)/2, sizeof(int));\n    if (values == NULL)\n        return false;\n    sc->max = max;\n    sc->values = values;\n    for (int n = 1; n <= max; ++n) {\n        for (int k = 1; k < n; ++k) {\n            int s1 = stirling_number2(sc, n - 1, k - 1);\n            int s2 = stirling_number2(sc, n - 1, k);\n            values[n*(n-1)/2 + k - 1] = s1 + s2 * k;\n        }\n    }\n    return true;\n}\n\nvoid stirling_cache_destroy(stirling_cache* sc) {\n    free(sc->values);\n    sc->values = NULL;\n}\n\nvoid print_stirling_numbers(stirling_cache* sc, int max) {\n    printf(\"Stirling numbers of the second kind:\\nn/k\");\n    for (int k = 0; k <= max; ++k)\n        printf(k == 0 ? \"%2d\" : \"%8d\", k);\n    printf(\"\\n\");\n    for (int n = 0; n <= max; ++n) {\n        printf(\"%2d \", n);\n        for (int k = 0; k <= n; ++k)\n            printf(k == 0 ? \"%2d\" : \"%8d\", stirling_number2(sc, n, k));\n        printf(\"\\n\");\n    }\n}\n\nint main() {\n    stirling_cache sc = { 0 };\n    const int max = 12;\n    if (!stirling_cache_create(&sc, max)) {\n        fprintf(stderr, \"Out of memory\\n\");\n        return 1;\n    }\n    print_stirling_numbers(&sc, max);\n    stirling_cache_destroy(&sc);\n    return 0;\n}\n"}
{"id": 45712, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n"}
{"id": 45713, "name": "Recaman's sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{0}\n    used := make(map[int]bool, 1001)\n    used[0] = true\n    used1000 := make(map[int]bool, 1001)\n    used1000[0] = true\n    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n        next := a[n-1] - n\n        if next < 1 || used[next] {\n            next += 2 * n\n        }\n        alreadyUsed := used[next]\n        a = append(a, next)\n\n        if !alreadyUsed {\n            used[next] = true\n            if next >= 0 && next <= 1000 {\n                used1000[next] = true\n            }\n        }\n\n        if n == 14 {\n            fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n        }\n\n        if !foundDup && alreadyUsed {\n            fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n            foundDup = true\n        }\n\n        if len(used1000) == 1001 {\n            fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmodule.h>\n\ntypedef int bool;\n\nint main() {\n    int i, n, k = 0, next, *a;\n    bool foundDup = FALSE;\n    gboolean alreadyUsed;\n    GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);\n    GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);\n    a = malloc(400000 * sizeof(int));\n    a[0] = 0;\n    g_hash_table_add(used, GINT_TO_POINTER(0));\n    g_hash_table_add(used1000, GINT_TO_POINTER(0));\n\n    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {\n        next = a[n - 1] - n;\n        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {\n            next += 2 * n;\n        }\n        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));\n        a[n] = next;\n\n        if (!alreadyUsed) {\n            g_hash_table_add(used, GINT_TO_POINTER(next));\n            if (next >= 0 && next <= 1000) {\n                g_hash_table_add(used1000, GINT_TO_POINTER(next));\n            }\n        }\n\n        if (n == 14) {\n            printf(\"The first 15 terms of the Recaman's sequence are: \");\n            printf(\"[\");\n            for (i = 0; i < 15; ++i) printf(\"%d \", a[i]);\n            printf(\"\\b]\\n\");\n        }\n\n        if (!foundDup && alreadyUsed) {\n            printf(\"The first duplicated term is a[%d] = %d\\n\", n, next);\n            foundDup = TRUE;\n        }\n        k = g_hash_table_size(used1000);\n\n        if (k == 1001) {\n            printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n);\n        }\n    }\n    g_hash_table_destroy(used);\n    g_hash_table_destroy(used1000);\n    free(a);\n    return 0;\n}\n"}
{"id": 45714, "name": "Memory allocation", "Go": "func inc(n int) {\n    x := n + 1\n    println(x)\n}\n", "C": "#include <stdlib.h>\n\n\n#define SIZEOF_MEMB (sizeof(int))\n#define NMEMB 100\n\nint main()\n{\n  int *ints = malloc(SIZEOF_MEMB*NMEMB);\n  \n  ints = realloc(ints, sizeof(int)*(NMEMB+1));\n  \n  int *int2 = calloc(NMEMB, SIZEOF_MEMB);\n  \n  free(ints); free(int2);\n  return 0;\n}\n"}
{"id": 45715, "name": "Tic-tac-toe", "Go": "package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"math/rand\"\n    \"os\"\n    \"strings\"\n)\n\nvar b []byte\n\nfunc printBoard() {\n    fmt.Printf(\"%s\\n%s\\n%s\\n\", b[0:3], b[3:6], b[6:9])\n}\n\nvar pScore, cScore int\nvar pMark, cMark byte = 'X', 'O'\nvar in = bufio.NewReader(os.Stdin)\n\nfunc main() {\n    b = make([]byte, 9)\n    fmt.Println(\"Play by entering a digit.\")\n    for {\n        \n        for i := range b {\n            b[i] = '1' + byte(i)\n        }\n        computerStart := cMark == 'X'\n        if computerStart {\n            fmt.Println(\"I go first, playing X's\")\n        } else {\n            fmt.Println(\"You go first, playing X's\")\n        }\n    TakeTurns:\n        for {\n            if !computerStart {\n                if !playerTurn() {\n                    return\n                }\n                if gameOver() {\n                    break TakeTurns\n                }\n\n            }\n            computerStart = false\n            computerTurn()\n            if gameOver() {\n                break TakeTurns\n            }\n        }\n        fmt.Println(\"Score: you\", pScore, \"me\", cScore)\n        fmt.Println(\"\\nLet's play again.\")\n    }\n}\n\nfunc playerTurn() bool {\n    var pm string\n    var err error\n    for i := 0; i < 3; i++ { \n        printBoard()\n        fmt.Printf(\"%c's move? \", pMark)\n        if pm, err = in.ReadString('\\n'); err != nil {\n            fmt.Println(err)\n            return false\n        }\n        pm = strings.TrimSpace(pm)\n        if pm >= \"1\" && pm <= \"9\" && b[pm[0]-'1'] == pm[0] {\n            x := pm[0] - '1'\n            b[x] = pMark\n            return true\n        }\n    }\n    fmt.Println(\"You're not playing right.\")\n    return false\n}\n\nvar choices = make([]int, 9)\n\nfunc computerTurn() {\n    printBoard()\n    var x int\n    defer func() {\n        fmt.Println(\"My move:\", x+1)\n        b[x] = cMark\n    }()\n    \n    block := -1\n    for _, l := range lines {\n        var mine, yours int\n        x = -1\n        for _, sq := range l {\n            switch b[sq] {\n            case cMark:\n                mine++\n            case pMark:\n                yours++\n            default:\n                x = sq\n            }\n        }\n        if mine == 2 && x >= 0 {\n            return \n        }\n        if yours == 2 && x >= 0 {\n            block = x\n        } \n    }\n    if block >= 0 {\n        x = block \n        return\n    }\n    \n    choices = choices[:0]\n    for i, sq := range b { \n        if sq == '1'+byte(i) {\n            choices = append(choices, i)\n        }\n    }\n    x = choices[rand.Intn(len(choices))]\n}   \n    \nfunc gameOver() bool {\n    \n    for _, l := range lines {\n        if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {\n            printBoard()\n            if b[l[0]] == cMark {\n                fmt.Println(\"I win!\")\n                cScore++\n                pMark, cMark = 'X', 'O'\n            } else {\n                fmt.Println(\"You win!\")\n                pScore++\n                pMark, cMark = 'O', 'X'\n            }\n            return true \n        } \n    }\n    \n    for i, sq := range b {\n        if sq == '1'+byte(i) {\n            return false\n        }\n    }\n    fmt.Println(\"Cat game.\")\n    pMark, cMark = cMark, pMark\n    return true\n}\n\nvar lines = [][]int{\n    {0, 1, 2}, \n    {3, 4, 5},\n    {6, 7, 8},\n    {0, 3, 6}, \n    {1, 4, 7},\n    {2, 5, 8},\n    {0, 4, 8}, \n    {2, 4, 6},\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\nint b[3][3]; \n\nint check_winner()\n{\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tif (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])\n\t\t\treturn b[i][0];\n\t\tif (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])\n\t\t\treturn b[0][i];\n\t}\n\tif (!b[1][1]) return 0;\n\n\tif (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];\n\tif (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];\n\n\treturn 0;\n}\n\nvoid showboard()\n{\n\tconst char *t = \"X O\";\n\tint i, j;\n\tfor (i = 0; i < 3; i++, putchar('\\n'))\n\t\tfor (j = 0; j < 3; j++)\n\t\t\tprintf(\"%c \", t[ b[i][j] + 1 ]);\n\tprintf(\"-----\\n\");\n}\n\n#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)\nint best_i, best_j;\nint test_move(int val, int depth)\n{\n\tint i, j, score;\n\tint best = -1, changed = 0;\n\n\tif ((score = check_winner())) return (score == val) ? 1 : -1;\n\n\tfor_ij {\n\t\tif (b[i][j]) continue;\n\n\t\tchanged = b[i][j] = val;\n\t\tscore = -test_move(-val, depth + 1);\n\t\tb[i][j] = 0;\n\n\t\tif (score <= best) continue;\n\t\tif (!depth) {\n\t\t\tbest_i = i;\n\t\t\tbest_j = j;\n\t\t}\n\t\tbest = score;\n\t}\n\n\treturn changed ? best : 0;\n}\n\nconst char* game(int user)\n{\n\tint i, j, k, move, win = 0;\n\tfor_ij b[i][j] = 0;\n\n\tprintf(\"Board postions are numbered so:\\n1 2 3\\n4 5 6\\n7 8 9\\n\");\n\tprintf(\"You have O, I have X.\\n\\n\");\n\tfor (k = 0; k < 9; k++, user = !user) {\n\t\twhile(user) {\n\t\t\tprintf(\"your move: \");\n\t\t\tif (!scanf(\"%d\", &move)) {\n\t\t\t\tscanf(\"%*s\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (--move < 0 || move >= 9) continue;\n\t\t\tif (b[i = move / 3][j = move % 3]) continue;\n\n\t\t\tb[i][j] = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (!user) {\n\t\t\tif (!k) { \n\t\t\t\tbest_i = rand() % 3;\n\t\t\t\tbest_j = rand() % 3;\n\t\t\t} else\n\t\t\t\ttest_move(-1, 0);\n\n\t\t\tb[best_i][best_j] = -1;\n\t\t\tprintf(\"My move: %d\\n\", best_i * 3 + best_j + 1);\n\t\t}\n\n\t\tshowboard();\n\t\tif ((win = check_winner())) \n\t\t\treturn win == 1 ? \"You win.\\n\\n\": \"I win.\\n\\n\";\n\t}\n\treturn \"A draw.\\n\\n\";\n}\n\nint main()\n{\n\tint first = 0;\n\twhile (1) printf(\"%s\", game(first = !first));\n\treturn 0;\n}\n"}
{"id": 45716, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n"}
{"id": 45717, "name": "Integer sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1;; i++ {\n        fmt.Println(i)\n    }\n}\n", "C": "#include <stdio.h>\n\nint main()\n{\n\tunsigned int i = 0;\n\twhile (++i) printf(\"%u\\n\", i);\n\n\treturn 0;\n}\n"}
{"id": 45718, "name": "Entropy_Narcissist", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 45719, "name": "Entropy_Narcissist", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"io/ioutil\"\n    \"log\"\n    \"math\"\n    \"os\"\n    \"runtime\"\n)\n\nfunc main() {\n    _, src, _, _ := runtime.Caller(0)\n    fmt.Println(\"Source file entropy:\", entropy(src))\n    fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n    d, err := ioutil.ReadFile(file)\n    if err != nil {\n        log.Fatal(err)\n    }\n    var f [256]float64\n    for _, b := range d {\n        f[b]++\n    }\n    hm := 0.\n    for _, c := range f {\n        if c > 0 {\n            hm += c * math.Log2(c)\n        }\n    }\n    l := float64(len(d))\n    return math.Log2(l) - hm/l\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n\n#define MAXLEN 961 \n\nint makehist(char *S,int *hist,int len){\n\tint wherechar[256];\n\tint i,histlen;\n\thistlen=0;\n\tfor(i=0;i<256;i++)wherechar[i]=-1;\n\tfor(i=0;i<len;i++){\n\t\tif(wherechar[(int)S[i]]==-1){\n\t\t\twherechar[(int)S[i]]=histlen;\n\t\t\thistlen++;\n\t\t}\n\t\thist[wherechar[(int)S[i]]]++;\n\t}\n\treturn histlen;\n}\n\ndouble entropy(int *hist,int histlen,int len){\n\tint i;\n\tdouble H;\n\tH=0;\n\tfor(i=0;i<histlen;i++){\n\t\tH-=(double)hist[i]/len*log2((double)hist[i]/len);\n\t}\n\treturn H;\n}\n\nint main(void){\n\tchar S[MAXLEN];\n\tint len,*hist,histlen;\n\tdouble H;\n\tFILE *f;\n\tf=fopen(\"entropy.c\",\"r\");\n\tfor(len=0;!feof(f);len++)S[len]=fgetc(f);\n\tS[--len]='\\0';\n\thist=(int*)calloc(len,sizeof(int));\n\thistlen=makehist(S,hist,len);\n\t\n\tH=entropy(hist,histlen,len);\n\tprintf(\"%lf\\n\",H);\n\treturn 0;\n}\n"}
{"id": 45720, "name": "DNS query", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n)\n\nfunc main() {\n    if addrs, err := net.LookupHost(\"www.kame.net\"); err == nil {\n        fmt.Println(addrs)\n    } else {\n        fmt.Println(err)\n    }\n}\n", "C": "#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\t\t\n#include <stdio.h>\t\t\n#include <stdlib.h>\t\t\n#include <string.h>\t\t\n\nint\nmain()\n{\n\tstruct addrinfo hints, *res, *res0;\n\tint error;\n\tchar host[NI_MAXHOST];\n\n\t\n\tmemset(&hints, 0, sizeof hints);\n\thints.ai_family = PF_UNSPEC;     \n\thints.ai_socktype = SOCK_DGRAM;  \n\n\t\n\terror = getaddrinfo(\"www.kame.net\", NULL, &hints, &res0);\n\tif (error) {\n\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\texit(1);\n\t}\n\n\t\n\tfor (res = res0; res; res = res->ai_next) {\n\t\t\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen,\n\t\t    host, sizeof host, NULL, 0, NI_NUMERICHOST);\n\n\t\tif (error) {\n\t\t\tfprintf(stderr, \"%s\\n\", gai_strerror(error));\n\t\t} else {\n\t\t\t\n\t\t\tprintf(\"%s\\n\", host);\n\t\t}\n\t}\n\n\t\n\tfreeaddrinfo(res0);\n\n\treturn 0;\n}\n"}
{"id": 45721, "name": "Peano curve", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar points []gg.Point\n\nconst width = 81\n\nfunc peano(x, y, lg, i1, i2 int) {\n    if lg == 1 {\n        px := float64(width-x) * 10\n        py := float64(width-y) * 10\n        points = append(points, gg.Point{px, py})\n        return\n    }\n    lg /= 3\n    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)\n    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)\n    peano(x+lg, y+lg, lg, i1, 1-i2)\n    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)\n    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)\n    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)\n    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)\n    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)\n    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)\n}\n\nfunc main() {\n    peano(0, 0, width, 0, 0)\n    dc := gg.NewContext(820, 820)\n    dc.SetRGB(1, 1, 1) \n    dc.Clear()\n    for _, p := range points {\n        dc.LineTo(p.X, p.Y)\n    }\n    dc.SetRGB(1, 0, 1) \n    dc.SetLineWidth(1)\n    dc.Stroke()\n    dc.SavePNG(\"peano.png\")\n}\n", "C": "\n\n#include <graphics.h>\n#include <math.h>\n\nvoid Peano(int x, int y, int lg, int i1, int i2) {\n\n\tif (lg == 1) {\n\t\tlineto(3*x,3*y);\n\t\treturn;\n\t}\n\t\n\tlg = lg/3;\n\tPeano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2);\n\tPeano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2);\n\tPeano(x+lg, y+lg, lg, i1, 1-i2);\n\tPeano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2);\n\tPeano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2);\n\tPeano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2);\n\tPeano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2);\n\tPeano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2);\n\tPeano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2);\n}\n\nint main(void) {\n\n\tinitwindow(1000,1000,\"Peano, Peano\");\n\n\tPeano(0, 0, 1000, 0, 0); \n\t\n\tgetch();\n\tcleardevice();\n\t\n\treturn 0;\n}\n"}
{"id": 45722, "name": "Seven-sided dice from five-sided dice", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\n\nfunc dice5() int {\n    return rand.Intn(5) + 1\n}\n\n\nfunc dice7() (i int) {\n    for {\n        i = 5*dice5() + dice5()\n        if i < 27 {\n            break\n        }\n    }\n    return (i / 3) - 1\n}\n\n\n\n\n\n\n\n\n\n\nfunc distCheck(f func() int, n int,\n    repeats int, delta float64) (max float64, flatEnough bool) {\n    count := make([]int, n)\n    for i := 0; i < repeats; i++ {\n        count[f()-1]++\n    }\n    expected := float64(repeats) / float64(n)\n    for _, c := range count {\n        max = math.Max(max, math.Abs(float64(c)-expected))\n    }\n    return max, max < delta\n}\n\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    const calls = 1000000\n    max, flatEnough := distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n    max, flatEnough = distCheck(dice7, 7, calls, 500)\n    fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "C": "int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n \nint rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\nint main()\n{\n\tprintf(check(rand5, 5, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\tprintf(check(rand7, 7, 1000000, .05) ? \"flat\\n\" : \"not flat\\n\");\n\treturn 0;\n}\n"}
{"id": 45723, "name": "Solve the no connection puzzle", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tp, tests, swaps := Solution()\n\tfmt.Println(p)\n\tfmt.Println(\"Tested\", tests, \"positions and did\", swaps, \"swaps.\")\n}\n\n\n\nconst conn = `\n       A   B\n      /|\\ /|\\\n     / | X | \\\n    /  |/ \\|  \\\n   C - D - E - F\n    \\  |\\ /|  /\n     \\ | X | /\n      \\|/ \\|/\n       G   H`\n\nvar connections = []struct{ a, b int }{\n\t{0, 2}, {0, 3}, {0, 4}, \n\t{1, 3}, {1, 4}, {1, 5}, \n\t{6, 2}, {6, 3}, {6, 4}, \n\t{7, 3}, {7, 4}, {7, 5}, \n\t{2, 3}, {3, 4}, {4, 5}, \n}\n\ntype pegs [8]int\n\n\n\n\nfunc (p *pegs) Valid() bool {\n\tfor _, c := range connections {\n\t\tif absdiff(p[c.a], p[c.b]) <= 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc Solution() (p *pegs, tests, swaps int) {\n\tvar recurse func(int) bool\n\trecurse = func(i int) bool {\n\t\tif i >= len(p)-1 {\n\t\t\ttests++\n\t\t\treturn p.Valid()\n\t\t}\n\t\t\n\t\tfor j := i; j < len(p); j++ {\n\t\t\tswaps++\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t\tif recurse(i + 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tp[i], p[j] = p[j], p[i]\n\t\t}\n\t\treturn false\n\t}\n\tp = &pegs{1, 2, 3, 4, 5, 6, 7, 8}\n\trecurse(0)\n\treturn\n}\n\nfunc (p *pegs) String() string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif 'A' <= r && r <= 'H' {\n\t\t\treturn rune(p[r-'A'] + '0')\n\t\t}\n\t\treturn r\n\t}, conn)\n}\n\nfunc absdiff(a, b int) int {\n\tif a > b {\n\t\treturn a - b\n\t}\n\treturn b - a\n}\n", "C": "#include <stdbool.h>\n#include <stdio.h>\n#include <math.h>\n\nint connections[15][2] = {\n    {0, 2}, {0, 3}, {0, 4}, \n    {1, 3}, {1, 4}, {1, 5}, \n    {6, 2}, {6, 3}, {6, 4}, \n    {7, 3}, {7, 4}, {7, 5}, \n    {2, 3}, {3, 4}, {4, 5}, \n};\n\nint pegs[8];\nint num = 0;\n\nbool valid() {\n    int i;\n    for (i = 0; i < 15; i++) {\n        if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid swap(int *a, int *b) {\n    int t = *a;\n    *a = *b;\n    *b = t;\n}\n\nvoid printSolution() {\n    printf(\"----- %d -----\\n\", num++);\n    printf(\"  %d %d\\n\",  pegs[0], pegs[1]);\n    printf(\"%d %d %d %d\\n\", pegs[2], pegs[3], pegs[4], pegs[5]);\n    printf(\"  %d %d\\n\",  pegs[6], pegs[7]);\n    printf(\"\\n\");\n}\n\nvoid solution(int le, int ri) {\n    if (le == ri) {\n        if (valid()) {\n            printSolution();\n        }\n    } else {\n        int i;\n        for (i = le; i <= ri; i++) {\n            swap(pegs + le, pegs + i);\n            solution(le + 1, ri);\n            swap(pegs + le, pegs + i);\n        }\n    }\n}\n\nint main() {\n    int i;\n    for (i = 0; i < 8; i++) {\n        pegs[i] = i + 1;\n    }\n\n    solution(0, 8 - 1);\n    return 0;\n}\n"}
{"id": 45724, "name": "Magnanimous numbers", "Go": "package main\n\nimport \"fmt\"\n\n\nfunc isPrime(n uint64) bool {\n    switch {\n    case n < 2:\n        return false\n    case n%2 == 0:\n        return n == 2\n    case n%3 == 0:\n        return n == 3\n    default:\n        d := uint64(5)\n        for d*d <= n {\n            if n%d == 0 {\n                return false\n            }\n            d += 2\n            if n%d == 0 {\n                return false\n            }\n            d += 4\n        }\n        return true\n    }\n}\n\nfunc ord(n int) string {\n    m := n % 100\n    if m >= 4 && m <= 20 {\n        return fmt.Sprintf(\"%dth\", n)\n    }\n    m %= 10\n    suffix := \"th\"\n    if m < 4 {\n        switch m {\n        case 1:\n            suffix = \"st\"\n        case 2:\n            suffix = \"nd\"\n        case 3:\n            suffix = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, suffix)\n}\n\nfunc isMagnanimous(n uint64) bool {\n    if n < 10 {\n        return true\n    }\n    for p := uint64(10); ; p *= 10 {\n        q := n / p\n        r := n % p\n        if !isPrime(q + r) {\n            return false\n        }\n        if q < 10 {\n            break\n        }\n    }\n    return true\n}\n\nfunc listMags(from, thru, digs, perLine int) {\n    if from < 2 {\n        fmt.Println(\"\\nFirst\", thru, \"magnanimous numbers:\")\n    } else {\n        fmt.Printf(\"\\n%s through %s magnanimous numbers:\\n\", ord(from), ord(thru))\n    }\n    for i, c := uint64(0), 0; c < thru; i++ {\n        if isMagnanimous(i) {\n            c++\n            if c >= from {\n                fmt.Printf(\"%*d \", digs, i)\n                if c%perLine == 0 {\n                    fmt.Println()\n                }\n            }\n        }\n    }\n}\n\nfunc main() {\n    listMags(1, 45, 3, 15)\n    listMags(241, 250, 1, 10)\n    listMags(391, 400, 1, 10)\n}\n", "C": "#include <stdio.h> \n#include <string.h>\n\ntypedef int bool;\ntypedef unsigned long long ull;\n\n#define TRUE 1\n#define FALSE 0\n\n\nbool is_prime(ull n) {\n    ull d;\n    if (n < 2) return FALSE;\n    if (!(n % 2)) return n == 2;\n    if (!(n % 3)) return n == 3;\n    d = 5;\n    while (d * d <= n) {\n        if (!(n % d)) return FALSE;\n        d += 2;\n        if (!(n % d)) return FALSE;\n        d += 4;\n    }\n    return TRUE;\n}\n\nvoid ord(char *res, int n) {\n    char suffix[3];\n    int m = n % 100;\n    if (m >= 4 && m <= 20) {\n        sprintf(res,\"%dth\", n);\n        return;\n    }\n    switch(m % 10) {\n        case 1:\n            strcpy(suffix, \"st\");\n            break;\n        case 2:\n            strcpy(suffix, \"nd\");\n            break;\n        case 3:\n            strcpy(suffix, \"rd\");\n            break;\n        default:\n            strcpy(suffix, \"th\");\n            break;\n    }\n    sprintf(res, \"%d%s\", n, suffix);\n}\n\nbool is_magnanimous(ull n) {\n    ull p, q, r;\n    if (n < 10) return TRUE;\n    for (p = 10; ; p *= 10) {\n        q = n / p;\n        r = n % p;\n        if (!is_prime(q + r)) return FALSE;\n        if (q < 10) break;\n    }\n    return TRUE;\n}\n\nvoid list_mags(int from, int thru, int digs, int per_line) {\n    ull i = 0;\n    int c = 0;\n    char res1[13], res2[13];\n    if (from < 2) {\n        printf(\"\\nFirst %d magnanimous numbers:\\n\", thru);\n    } else {\n        ord(res1, from);\n        ord(res2, thru);\n        printf(\"\\n%s through %s magnanimous numbers:\\n\", res1, res2);\n    }\n    for ( ; c < thru; ++i) {\n        if (is_magnanimous(i)) {\n            if (++c >= from) {\n                printf(\"%*llu \", digs, i);\n                if (!(c % per_line)) printf(\"\\n\");\n            }\n        }\n    }\n}\n \nint main() {\n    list_mags(1, 45, 3, 15);\n    list_mags(241, 250, 1, 10);\n    list_mags(391, 400, 1, 10);\n    return 0;\n}\n"}
{"id": 45725, "name": "Extensible prime generator", "Go": "package main\n\nimport (\n    \"container/heap\"\n    \"fmt\"\n)\n\nfunc main() {\n    p := newP()\n    fmt.Print(\"First twenty: \")\n    for i := 0; i < 20; i++ {\n        fmt.Print(p(), \" \")\n    }\n    fmt.Print(\"\\nBetween 100 and 150: \")\n    n := p()\n    for n <= 100 {\n        n = p()\n    }\n    for ; n < 150; n = p() {\n        fmt.Print(n, \" \")\n    }\n    for n <= 7700 {\n        n = p()\n    }\n    c := 0\n    for ; n < 8000; n = p() {\n        c++\n    }\n    fmt.Println(\"\\nNumber beween 7,700 and 8,000:\", c)\n    p = newP()\n    for i := 1; i < 10000; i++ {\n        p()\n    }\n    fmt.Println(\"10,000th prime:\", p())\n}\n\nfunc newP() func() int {\n    n := 1\n    var pq pQueue\n    top := &pMult{2, 4, 0}\n    return func() int {\n        for {\n            n++\n            if n < top.pMult { \n                heap.Push(&pq, &pMult{prime: n, pMult: n * n})\n                top = pq[0]\n                return n\n            }\n            \n            for top.pMult == n {\n                top.pMult += top.prime\n                heap.Fix(&pq, 0)\n                top = pq[0]\n            }\n        }\n    }\n}\n\ntype pMult struct {\n    prime int\n    pMult int\n    index int\n}\n\ntype pQueue []*pMult\n\nfunc (q pQueue) Len() int           { return len(q) }\nfunc (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }\nfunc (q pQueue) Swap(i, j int) {\n    q[i], q[j] = q[j], q[i]\n    q[i].index = i\n    q[j].index = j\n}\nfunc (p *pQueue) Push(x interface{}) {\n    q := *p\n    e := x.(*pMult)\n    e.index = len(q)\n    *p = append(q, e)\n}\nfunc (p *pQueue) Pop() interface{} {\n    q := *p\n    last := len(q) - 1\n    e := q[last]\n    *p = q[:last]\n    return e\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#define CHUNK_BYTES (32 << 8)\n#define CHUNK_SIZE (CHUNK_BYTES << 6)\n\nint field[CHUNK_BYTES];\n#define GET(x) (field[(x)>>6] &  1<<((x)>>1&31))\n#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))\n\ntypedef unsigned uint;\ntypedef struct {\n        uint *e;\n        uint cap, len;\n} uarray;\nuarray primes, offset;\n\nvoid push(uarray *a, uint n)\n{\n        if (a->len >= a->cap) {\n                if (!(a->cap *= 2)) a->cap = 16;\n                a->e = realloc(a->e, sizeof(uint) * a->cap);\n        }\n        a->e[a->len++] = n;\n}\n\nuint low;\nvoid init(void)\n{\n        uint p, q;\n\n        unsigned char f[1<<16];\n        memset(f, 0, sizeof(f));\n        push(&primes, 2);\n        push(&offset, 0);\n        for (p = 3; p < 1<<16; p += 2) {\n                if (f[p]) continue;\n                for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;\n                push(&primes, p);\n                push(&offset, q);\n        }\n        low = 1<<16;\n}\n\nvoid sieve(void)\n{\n        uint i, p, q, hi, ptop;\n        if (!low) init();\n\n        memset(field, 0, sizeof(field));\n\n        hi = low + CHUNK_SIZE;\n        ptop = sqrt(hi) * 2 + 1;\n\n        for (i = 1; (p = primes.e[i]*2) < ptop; i++) {\n                for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)\n                        SET(q);\n                offset.e[i] = q + low;\n        }\n\n        for (p = 1; p < CHUNK_SIZE; p += 2)\n                if (!GET(p)) push(&primes, low + p);\n\n        low = hi;\n}\n\nint main(void)\n{\n        uint i, p, c;\n\n        while (primes.len < 20) sieve();\n        printf(\"First 20:\");\n        for (i = 0; i < 20; i++)\n                printf(\" %u\", primes.e[i]);\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 150) sieve();\n        printf(\"Between 100 and 150:\");\n        for (i = 0; i < primes.len; i++) {\n                if ((p = primes.e[i]) >= 100 && p < 150)\n                        printf(\" %u\", primes.e[i]);\n        }\n        putchar('\\n');\n\n        while (primes.e[primes.len-1] < 8000) sieve();\n        for (i = c = 0; i < primes.len; i++)\n                if ((p = primes.e[i]) >= 7700 && p < 8000) c++;\n        printf(\"%u primes between 7700 and 8000\\n\", c);\n\n        for (c = 10; c <= 100000000; c *= 10) {\n                while (primes.len < c) sieve();\n                printf(\"%uth prime: %u\\n\", c, primes.e[c-1]);\n        }\n\n        return 0;\n}\n"}
{"id": 45726, "name": "Rock-paper-scissors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define LEN 3 \n\n\nint rand_idx(double *p, int n)\n{\n\tdouble s = rand() / (RAND_MAX + 1.0);\n\tint i;\n\tfor (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);\n\treturn i;\n}\n\nint main()\n{\n\tint user_action, my_action;\n\tint user_rec[] = {0, 0, 0};\n\tconst char *names[] = { \"Rock\", \"Paper\", \"Scissors\" };\n\tchar str[2];\n\tconst char *winner[] = { \"We tied.\", \"Meself winned.\", \"You win.\" };\n\tdouble  p[LEN] = { 1./3, 1./3, 1./3 };\n \n\twhile (1) {\n\t\tmy_action = rand_idx(p,LEN);\n \n\t\tprintf(\"\\nYour choice [1-3]:\\n\"\n\t\t\t\"  1. Rock\\n  2. Paper\\n  3. Scissors\\n> \");\n \n\t\t\n\t\tif (!scanf(\"%d\", &user_action)) {\n\t\t\tscanf(\"%1s\", str);\n\t\t\tif (*str == 'q') {\n\t\t\t\tprintf(\"Your choices [rock : %d , paper :  %d , scissors %d] \",user_rec[0],user_rec[1], user_rec[2]); \n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tuser_action --;\n\t\tif (user_action > 2 || user_action < 0) {\n\t\t\tprintf(\"invalid choice; again\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tprintf(\"You chose %s; I chose %s. %s\\n\",\n\t\t\tnames[user_action], names[my_action],\n\t\t\twinner[(my_action - user_action + 3) % 3]);\n \n\t\tuser_rec[user_action]++;\n\t}\n}\n"}
{"id": 45727, "name": "Rock-paper-scissors", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst rps = \"rps\"\n\nvar msg = []string{\n    \"Rock breaks scissors\",\n    \"Paper covers rock\",\n    \"Scissors cut paper\",\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(\"Rock Paper Scissors\")\n    fmt.Println(\"Enter r, p, or s as your play.  Anything else ends the game.\")\n    fmt.Println(\"Running score shown as <your wins>:<my wins>\")\n    var pi string \n    var aScore, pScore int\n    sl := 3               \n    pcf := make([]int, 3) \n    var plays int\n    aChoice := rand.Intn(3) \n    for {\n        \n        fmt.Print(\"Play: \")\n        _, err := fmt.Scanln(&pi)  \n        if err != nil || len(pi) != 1 {\n            break\n        }\n        pChoice := strings.Index(rps, pi)\n        if pChoice < 0 {\n            break\n        }\n        pcf[pChoice]++\n        plays++\n\n        \n        fmt.Printf(\"My play:%s%c.  \", strings.Repeat(\" \", sl-2), rps[aChoice])\n        switch (aChoice - pChoice + 3) % 3 {\n        case 0:\n            fmt.Println(\"Tie.\")\n        case 1:\n            fmt.Printf(\"%s.  My point.\\n\", msg[aChoice])\n            aScore++\n        case 2:\n            fmt.Printf(\"%s.  Your point.\\n\", msg[pChoice])\n            pScore++\n        }\n\n        \n        sl, _ = fmt.Printf(\"%d:%d  \", pScore, aScore)\n\n        \n        switch rn := rand.Intn(plays); {\n        case rn < pcf[0]:\n            aChoice = 1\n        case rn < pcf[0]+pcf[1]:\n            aChoice = 2\n        default:\n            aChoice = 0\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#define LEN 3 \n\n\nint rand_idx(double *p, int n)\n{\n\tdouble s = rand() / (RAND_MAX + 1.0);\n\tint i;\n\tfor (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);\n\treturn i;\n}\n\nint main()\n{\n\tint user_action, my_action;\n\tint user_rec[] = {0, 0, 0};\n\tconst char *names[] = { \"Rock\", \"Paper\", \"Scissors\" };\n\tchar str[2];\n\tconst char *winner[] = { \"We tied.\", \"Meself winned.\", \"You win.\" };\n\tdouble  p[LEN] = { 1./3, 1./3, 1./3 };\n \n\twhile (1) {\n\t\tmy_action = rand_idx(p,LEN);\n \n\t\tprintf(\"\\nYour choice [1-3]:\\n\"\n\t\t\t\"  1. Rock\\n  2. Paper\\n  3. Scissors\\n> \");\n \n\t\t\n\t\tif (!scanf(\"%d\", &user_action)) {\n\t\t\tscanf(\"%1s\", str);\n\t\t\tif (*str == 'q') {\n\t\t\t\tprintf(\"Your choices [rock : %d , paper :  %d , scissors %d] \",user_rec[0],user_rec[1], user_rec[2]); \n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tuser_action --;\n\t\tif (user_action > 2 || user_action < 0) {\n\t\t\tprintf(\"invalid choice; again\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tprintf(\"You chose %s; I chose %s. %s\\n\",\n\t\t\tnames[user_action], names[my_action],\n\t\t\twinner[(my_action - user_action + 3) % 3]);\n \n\t\tuser_rec[user_action]++;\n\t}\n}\n"}
{"id": 45728, "name": "Create a two-dimensional array at runtime", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n   int user1 = 0, user2 = 0;\n   printf(\"Enter two integers.  Space delimited, please:  \");\n   scanf(\"%d %d\",&user1, &user2);\n   int array[user1][user2];\n   array[user1/2][user2/2] = user1 + user2;\n   printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n\n   return 0;\n}\n"}
{"id": 45729, "name": "Create a two-dimensional array at runtime", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    var row, col int\n    fmt.Print(\"enter rows cols: \")\n    fmt.Scan(&row, &col)\n\n    \n    a := make([][]int, row)\n    for i := range a {\n        a[i] = make([]int, col)\n    }\n\n    \n    fmt.Println(\"a[0][0] =\", a[0][0])\n\n    \n    a[row-1][col-1] = 7\n\n    \n    fmt.Printf(\"a[%d][%d] = %d\\n\", row-1, col-1, a[row-1][col-1])\n\n    \n    a = nil\n    \n}\n", "C": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n   int user1 = 0, user2 = 0;\n   printf(\"Enter two integers.  Space delimited, please:  \");\n   scanf(\"%d %d\",&user1, &user2);\n   int array[user1][user2];\n   array[user1/2][user2/2] = user1 + user2;\n   printf(\"array[%d][%d] is %d\\n\",user1/2,user2/2,array[user1/2][user2/2]);\n\n   return 0;\n}\n"}
{"id": 45730, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n"}
{"id": 45731, "name": "Chinese remainder theorem", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n    p := new(big.Int).Set(n[0])\n    for _, n1 := range n[1:] {\n        p.Mul(p, n1)\n    }\n    var x, q, s, z big.Int\n    for i, n1 := range n {\n        q.Div(p, n1)\n        z.GCD(nil, &s, n1, &q)\n        if z.Cmp(one) != 0 {\n            return nil, fmt.Errorf(\"%d not coprime\", n1)\n        }\n        x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n    }\n    return x.Mod(&x, p), nil\n}\n\nfunc main() {\n    n := []*big.Int{\n        big.NewInt(3),\n        big.NewInt(5),\n        big.NewInt(7),\n    }\n    a := []*big.Int{\n        big.NewInt(2),\n        big.NewInt(3),\n        big.NewInt(2),\n    }\n    fmt.Println(crt(a, n))\n}\n", "C": "#include <stdio.h>\n\n\nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n\nint chinese_remainder(int *n, int *a, int len)\n{\n\tint p, i, prod = 1, sum = 0;\n\n\tfor (i = 0; i < len; i++) prod *= n[i];\n\n\tfor (i = 0; i < len; i++) {\n\t\tp = prod / n[i];\n\t\tsum += a[i] * mul_inv(p, n[i]) * p;\n\t}\n\n\treturn sum % prod;\n}\n\nint main(void)\n{\n\tint n[] = { 3, 5, 7 };\n\tint a[] = { 2, 3, 2 };\n\n\tprintf(\"%d\\n\", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));\n\treturn 0;\n}\n"}
{"id": 45732, "name": "Vigenère cipher_Cryptanalysis", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar encoded = \n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [26]float64{\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n}\n\nfunc sum(a []float64) (sum float64) {\n    for _, f := range a {\n        sum += f\n    }\n    return\n}\n\nfunc bestMatch(a []float64) int {\n    sum := sum(a)\n    bestFit, bestRotate := 1e100, 0\n    for rotate := 0; rotate < 26; rotate++ {\n        fit := 0.0\n        for i := 0; i < 26; i++ {\n            d := a[(i+rotate)%26]/sum - freq[i]\n            fit += d * d / freq[i]\n        }\n        if fit < bestFit {\n            bestFit, bestRotate = fit, rotate\n        }\n    }\n    return bestRotate\n}\n\nfunc freqEveryNth(msg []int, key []byte) float64 {\n    l := len(msg)\n    interval := len(key)\n    out := make([]float64, 26)\n    accu := make([]float64, 26)\n    for j := 0; j < interval; j++ {\n        for k := 0; k < 26; k++ {\n            out[k] = 0.0\n        }\n        for i := j; i < l; i += interval {\n            out[msg[i]]++\n        }\n        rot := bestMatch(out)\n        key[j] = byte(rot + 65)\n        for i := 0; i < 26; i++ {\n            accu[i] += out[(i+rot)%26]\n        }\n    }\n    sum := sum(accu)\n    ret := 0.0\n    for i := 0; i < 26; i++ {\n        d := accu[i]/sum - freq[i]\n        ret += d * d / freq[i]\n    }\n    return ret\n}\n\nfunc decrypt(text, key string) string {\n    var sb strings.Builder\n    ki := 0\n    for _, c := range text {\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        ci := (c - rune(key[ki]) + 26) % 26\n        sb.WriteRune(ci + 65)\n        ki = (ki + 1) % len(key)\n    }\n    return sb.String()\n}\n\nfunc main() {\n    enc := strings.Replace(encoded, \" \", \"\", -1)\n    txt := make([]int, len(enc))\n    for i := 0; i < len(txt); i++ {\n        txt[i] = int(enc[i] - 'A')\n    }\n    bestFit, bestKey := 1e100, \"\"\n    fmt.Println(\"  Fit     Length   Key\")\n    for j := 1; j <= 26; j++ {\n        key := make([]byte, j)\n        fit := freqEveryNth(txt, key)\n        sKey := string(key)\n        fmt.Printf(\"%f    %2d     %s\", fit, j, sKey)\n        if fit < bestFit {\n            bestFit, bestKey = fit, sKey\n            fmt.Print(\" <--- best so far\")\n        }\n        fmt.Println()\n    }\n    fmt.Println(\"\\nBest key :\", bestKey)\n    fmt.Printf(\"\\nDecrypted text:\\n%s\\n\", decrypt(enc, bestKey))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *encoded =\n    \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\"\n    \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\"\n    \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\"\n    \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\"\n    \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\"\n    \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\"\n    \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\"\n    \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\"\n    \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\"\n    \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\"\n    \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\"\n    \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\"\n    \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\"\n    \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\"\n    \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\"\n    \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\"\n    \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst double freq[] = {\n    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n    0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n\nint best_match(const double *a, const double *b) {\n    double sum = 0, fit, d, best_fit = 1e100;\n    int i, rotate, best_rotate = 0;\n    for (i = 0; i < 26; i++)\n        sum += a[i];\n    for (rotate = 0; rotate < 26; rotate++) {\n        fit = 0;\n        for (i = 0; i < 26; i++) {\n            d = a[(i + rotate) % 26] / sum - b[i];\n            fit += d * d / b[i];\n        }\n\n        if (fit < best_fit) {\n            best_fit = fit;\n            best_rotate = rotate;\n        }\n    }\n\n    return best_rotate;\n}\n\ndouble freq_every_nth(const int *msg, int len, int interval, char *key) {\n    double sum, d, ret;\n    double out[26], accu[26] = {0};\n    int i, j, rot;\n\n    for (j = 0; j < interval; j++) {\n        for (i = 0; i < 26; i++)\n            out[i] = 0;\n        for (i = j; i < len; i += interval)\n            out[msg[i]]++;\n        key[j] = rot = best_match(out, freq);\n        key[j] += 'A';\n        for (i = 0; i < 26; i++)\n            accu[i] += out[(i + rot) % 26];\n    }\n\n    for (i = 0, sum = 0; i < 26; i++)\n        sum += accu[i];\n\n    for (i = 0, ret = 0; i < 26; i++) {\n        d = accu[i] / sum - freq[i];\n        ret += d * d / freq[i];\n    }\n\n    key[interval] = '\\0';\n    return ret;\n}\n\nint main() {\n    int txt[strlen(encoded)];\n    int len = 0, j;\n    char key[100];\n    double fit, best_fit = 1e100;\n\n    for (j = 0; encoded[j] != '\\0'; j++)\n        if (isupper(encoded[j]))\n            txt[len++] = encoded[j] - 'A';\n\n    for (j = 1; j < 30; j++) {\n        fit = freq_every_nth(txt, len, j, key);\n        printf(\"%f, key length: %2d, %s\", fit, j, key);\n        if (fit < best_fit) {\n            best_fit = fit;\n            printf(\" <--- best so far\");\n        }\n        printf(\"\\n\");\n    }\n\n    return 0;\n}\n"}
{"id": 45733, "name": "Pi", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\nmpz_t tmp1, tmp2, t5, t239, pows;\nvoid actan(mpz_t res, unsigned long base, mpz_t pows)\n{\n\tint i, neg = 1;\n\tmpz_tdiv_q_ui(res, pows, base);\n\tmpz_set(tmp1, res);\n\tfor (i = 3; ; i += 2) {\n\t\tmpz_tdiv_q_ui(tmp1, tmp1, base * base);\n\t\tmpz_tdiv_q_ui(tmp2, tmp1, i);\n\t\tif (mpz_cmp_ui(tmp2, 0) == 0) break;\n\t\tif (neg) mpz_sub(res, res, tmp2);\n\t\telse\t  mpz_add(res, res, tmp2);\n\t\tneg = !neg;\n\t}\n}\n\nchar * get_digits(int n, size_t* len)\n{\n\tmpz_ui_pow_ui(pows, 10, n + 20);\n\n\tactan(t5, 5, pows);\n\tmpz_mul_ui(t5, t5, 16);\n\n\tactan(t239, 239, pows);\n\tmpz_mul_ui(t239, t239, 4);\n\n\tmpz_sub(t5, t5, t239);\n\tmpz_ui_pow_ui(pows, 10, 20);\n\tmpz_tdiv_q(t5, t5, pows);\n\n\t*len = mpz_sizeinbase(t5, 10);\n\treturn mpz_get_str(0, 0, t5);\n}\n\nint main(int c, char **v)\n{\n\tunsigned long accu = 16384, done = 0;\n\tsize_t got;\n\tchar *s;\n\n\tmpz_init(tmp1);\n\tmpz_init(tmp2);\n\tmpz_init(t5);\n\tmpz_init(t239);\n\tmpz_init(pows);\n\n\twhile (1) {\n\t\ts = get_digits(accu, &got);\n\n\t\t\n\t\tgot -= 2; \n\t\twhile (s[got] == '0' || s[got] == '9') got--;\n\n\t\tprintf(\"%.*s\", (int)(got - done), s + done);\n\t\tfree(s);\n\n\t\tdone = got;\n\n\t\t\n\t\taccu *= 2;\n\t}\n\n\treturn 0;\n}\n"}
{"id": 45734, "name": "Hofstadter Q sequence", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n"}
{"id": 45735, "name": "Hofstadter Q sequence", "Go": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n    m = make(map[int]int)\n    m[1] = 1\n    m[2] = 1\n}\n\nfunc q(n int) (r int) {\n    if r = m[n]; r == 0 {\n        r = q(n-q(n-1)) + q(n-q(n-2))\n        m[n] = r\n    }\n    return\n}\n\nfunc main() {\n    initMap()\n    \n    for n := 1; n <= 10; n++ {\n        showQ(n)\n    }\n    \n    showQ(1000)\n    \n    count, p := 0, 1\n    for n := 2; n <= 1e5; n++ {\n        qn := q(n)\n        if qn < p {\n            count++\n        }\n        p = qn\n    }\n    fmt.Println(\"count:\", count)\n    \n    initMap()\n    showQ(1e6)\n}\n\nfunc showQ(n int) {\n    fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n#define N 100000\nint main()\n{\n\tint i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;\n\n\tq[1] = q[2] = 1;\n\n\tfor (i = 3; i <= N; i++)\n\t\tq[i] = q[i - q[i - 1]] + q[i - q[i - 2]];\n\t\t\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\"%d%c\", q[i], i == 10 ? '\\n' : ' ');\n\n\tprintf(\"%d\\n\", q[1000]);\n\n\tfor (flip = 0, i = 1; i < N; i++)\n\t\tflip += q[i] > q[i + 1];\n\n\tprintf(\"flips: %d\\n\", flip);\n\treturn 0;\n}\n"}
{"id": 45736, "name": "Y combinator", "Go": "package main\n\nimport \"fmt\"\n\ntype Func func(int) int\ntype FuncFunc func(Func) Func\ntype RecursiveFunc func (RecursiveFunc) Func\n\nfunc main() {\n\tfac := Y(almost_fac)\n\tfib := Y(almost_fib)\n\tfmt.Println(\"fac(10) = \", fac(10))\n\tfmt.Println(\"fib(10) = \", fib(10))\n}\n\nfunc Y(f FuncFunc) Func {\n\tg := func(r RecursiveFunc) Func {\n\t\treturn f(func(x int) int {\n\t\t\treturn r(r)(x)\n\t\t})\n\t}\n\treturn g(g)\n}\n\nfunc almost_fac(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 1 {\n\t\t\treturn 1\n\t\t}\n\t\treturn x * f(x-1)\n\t}\n}\n\nfunc almost_fib(f Func) Func {\n\treturn func(x int) int {\n\t\tif x <= 2 {\n\t\t\treturn 1\n\t\t}\n\t\treturn f(x-1)+f(x-2)\n\t}\n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n\n\ntypedef struct func_t *func;\ntypedef struct func_t {\n        func (*fn) (func, func);\n        func _;\n        int num;\n} func_t;\n\nfunc new(func(*f)(func, func), func _) {\n        func x = malloc(sizeof(func_t));\n        x->fn = f;\n        x->_ = _;       \n        x->num = 0;\n        return x;\n}\n\nfunc call(func f, func n) {\n        return f->fn(f, n);\n}\n\nfunc Y(func(*f)(func, func)) {\n        func g = new(f, 0);\n        g->_ = g;\n        return g;\n}\n\nfunc num(int n) {\n        func x = new(0, 0);\n        x->num = n;\n        return x;\n}\n\n\nfunc fac(func self, func n) {\n        int nn = n->num;\n        return nn > 1   ? num(nn * call(self->_, num(nn - 1))->num)\n                        : num(1);\n}\n\nfunc fib(func self, func n) {\n        int nn = n->num;\n        return nn > 1\n                ? num(  call(self->_, num(nn - 1))->num +\n                        call(self->_, num(nn - 2))->num )\n                : num(1);\n}\n\nvoid show(func n) { printf(\" %d\", n->num); }\n\nint main() {\n        int i;\n        func f = Y(fac);\n        printf(\"fac: \");\n        for (i = 1; i < 10; i++)\n                show( call(f, num(i)) );\n        printf(\"\\n\");\n\n        f = Y(fib);\n        printf(\"fib: \");\n        for (i = 1; i < 10; i++)\n                show( call(f, num(i)) );\n        printf(\"\\n\");\n\n        return 0;\n}\n"}
{"id": 45737, "name": "Return multiple values", "Go": "func addsub(x, y int) (int, int) {\n  return x + y, x - y\n}\n", "C": "#include<stdio.h>\n\ntypedef struct{\n\tint integer;\n\tfloat decimal;\n\tchar letter;\n\tchar string[100];\n\tdouble bigDecimal;\n}Composite;\n\nComposite example()\n{\n\tComposite C = {1, 2.3, 'a', \"Hello World\", 45.678};\n\treturn C;\n}\n\n\nint main()\n{\n\tComposite C = example();\n\n\tprintf(\"Values from a function returning a structure : { %d, %f, %c, %s, %f}\\n\", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);\n\n\treturn 0;\n}\n"}
{"id": 45738, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, const char *argv[]) {\n  const int max = 1000;\n  int *a = malloc(max * sizeof(int));\n  for (int n = 0; n < max - 1; n ++) {\n    for (int m = n - 1; m >= 0; m --) {\n      if (a[m] == a[n]) {\n        a[n+1] = n - m;\n        break;\n      }\n    }\n  }\n\n  printf(\"The first ten terms of the Van Eck sequence are:\\n\");\n  for (int i = 0; i < 10; i ++) printf(\"%d \", a[i]);\n  printf(\"\\n\\nTerms 991 to 1000 of the sequence are:\\n\");\n  for (int i = 990; i < 1000; i ++) printf(\"%d \", a[i]);\n  putchar('\\n');\n\n  return 0;\n}\n"}
{"id": 45739, "name": "Van Eck sequence", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    const max = 1000\n    a := make([]int, max) \n    for n := 0; n < max-1; n++ {\n        for m := n - 1;  m >= 0; m-- {\n            if a[m] == a[n] {\n                a[n+1] = n - m\n                break\n            }    \n        }\n    }\n    fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n    fmt.Println(a[:10])\n    fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n    fmt.Println(a[990:])\n}\n", "C": "#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, const char *argv[]) {\n  const int max = 1000;\n  int *a = malloc(max * sizeof(int));\n  for (int n = 0; n < max - 1; n ++) {\n    for (int m = n - 1; m >= 0; m --) {\n      if (a[m] == a[n]) {\n        a[n+1] = n - m;\n        break;\n      }\n    }\n  }\n\n  printf(\"The first ten terms of the Van Eck sequence are:\\n\");\n  for (int i = 0; i < 10; i ++) printf(\"%d \", a[i]);\n  printf(\"\\n\\nTerms 991 to 1000 of the sequence are:\\n\");\n  for (int i = 990; i < 1000; i ++) printf(\"%d \", a[i]);\n  putchar('\\n');\n\n  return 0;\n}\n"}
{"id": 45740, "name": "FTP", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/stacktic/ftp\"\n)\n\nfunc main() {\n\t\n\tconst (\n\t\thostport = \"localhost:21\"\n\t\tusername = \"anonymous\"\n\t\tpassword = \"anonymous\"\n\t\tdir      = \"pub\"\n\t\tfile     = \"somefile.bin\"\n\t)\n\n\tconn, err := ftp.Connect(hostport)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Quit()\n\tfmt.Println(conn)\n\n\tif err = conn.Login(username, password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = conn.ChangeDir(dir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(conn.CurrentDir())\n\tfiles, err := conn.List(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, f := range files {\n\t\tfmt.Printf(\"%v %12d %v %v\\n\", f.Time, f.Size, f.Type, f.Name)\n\t}\n\n\tr, err := conn.Retr(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tn, err := io.Copy(f, r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Wrote\", n, \"bytes to\", file)\n}\n", "C": "#include <ftplib.h>\n\nint main(void)\n{\n    netbuf *nbuf;\n\n    FtpInit();\n    FtpConnect(\"kernel.org\", &nbuf);\n    FtpLogin(\"anonymous\", \"\", nbuf);\n    FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);\n    FtpChdir(\"pub/linux/kernel\", nbuf);\n    FtpDir((void*)0, \".\", nbuf);\n    FtpGet(\"ftp.README\", \"README\", FTPLIB_ASCII, nbuf);\n    FtpQuit(nbuf);\n\n    return 0;\n}\n"}
{"id": 45741, "name": "24 game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <setjmp.h>\n#include <time.h>\n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom /= t;\n\t\tres->num /= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr/n/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); \n\t\tif (msg) {\n\t\t\t\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24.  Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good.  Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 45742, "name": "24 game", "Go": "package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '/':\n            stack[len(stack)-2] /= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n", "C": "#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <setjmp.h>\n#include <time.h>\n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom /= t;\n\t\tres->num /= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr/n/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); \n\t\tif (msg) {\n\t\t\t\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24.  Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good.  Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}\n"}
{"id": 45743, "name": "Loops_Continue", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 10; i++ {\n        fmt.Printf(\"%d\", i)\n        if i%5 == 0 {\n            fmt.Printf(\"\\n\")\n            continue\n        }\n        fmt.Printf(\", \")\n    }\n}\n", "C": "for(int i = 1;i <= 10; i++){\n   printf(\"%d\", i);\n   if(i % 5 == 0){\n      printf(\"\\n\");\n      continue;\n   }\n   printf(\", \");\n}\n"}
{"id": 45744, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n"}
{"id": 45745, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n"}
{"id": 45746, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n"}
{"id": 45747, "name": "Colour bars_Display", "Go": "package main\n\nimport \"github.com/fogleman/gg\"\n\nvar colors = [8]string{\n    \"000000\", \n    \"FF0000\", \n    \"00FF00\", \n    \"0000FF\", \n    \"FF00FF\", \n    \"00FFFF\", \n    \"FFFF00\", \n    \"FFFFFF\", \n}\n\nfunc drawBars(dc *gg.Context) {\n    w := float64(dc.Width() / len(colors))\n    h := float64(dc.Height())\n    for i := range colors {\n        dc.SetHexColor(colors[i])\n        dc.DrawRectangle(w*float64(i), 0, w, h)\n        dc.Fill()\n    }\n}\n\nfunc main() {\n    dc := gg.NewContext(400, 400)\n    drawBars(dc)\n    dc.SavePNG(\"color_bars.png\")\n}\n", "C": "#include<conio.h>\n\n#define COLOURS 8\n\nint main()\n{\n\tint colour=0,i,j,MAXROW,MAXCOL;\n\tstruct text_info tInfo;\n\tgettextinfo(&tInfo);\n\tMAXROW = tInfo.screenheight;\n\tMAXCOL = tInfo.screenwidth;\n\ttextbackground(BLACK);     \n\tclrscr();\n\t\n\tfor(colour=0;colour<COLOURS;colour++)\n\t{\n\t\tgetch();                              \n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1);\n\t\ttextbackground(colour);\n\t\tfor(j=0;j<MAXROW;j++){\n\t\t\tfor(i=0;i<MAXCOL/COLOURS;i++){\n\t\t\t\tcprintf(\" \");\n\t\t\t}\n\t\tgotoxy(1+colour*MAXCOL/COLOURS,1+j);\n\t\t}\n\t}\n\n\tgetch();\n\ttextbackground(BLACK);\n\n\treturn 0;\n}\n"}
{"id": 45748, "name": "LU decomposition", "Go": "package main\n\nimport \"fmt\"\n    \ntype matrix [][]float64\n\nfunc zero(n int) matrix {\n    r := make([][]float64, n)\n    a := make([]float64, n*n)\n    for i := range r {\n        r[i] = a[n*i : n*(i+1)]\n    } \n    return r \n}\n    \nfunc eye(n int) matrix {\n    r := zero(n)\n    for i := range r {\n        r[i][i] = 1\n    }\n    return r\n}   \n    \nfunc (m matrix) print(label string) {\n    if label > \"\" {\n        fmt.Printf(\"%s:\\n\", label)\n    }\n    for _, r := range m {\n        for _, e := range r {\n            fmt.Printf(\" %9.5f\", e)\n        }\n        fmt.Println()\n    }\n}\n\nfunc (a matrix) pivotize() matrix { \n    p := eye(len(a))\n    for j, r := range a {\n        max := r[j] \n        row := j\n        for i := j; i < len(a); i++ {\n            if a[i][j] > max {\n                max = a[i][j]\n                row = i\n            }\n        }\n        if j != row {\n            \n            p[j], p[row] = p[row], p[j]\n        }\n    } \n    return p\n}\n\nfunc (m1 matrix) mul(m2 matrix) matrix {\n    r := zero(len(m1))\n    for i, r1 := range m1 {\n        for j := range m2 {\n            for k := range m1 {\n                r[i][j] += r1[k] * m2[k][j]\n            }\n        }\n    }\n    return r\n}\n\nfunc (a matrix) lu() (l, u, p matrix) {\n    l = zero(len(a))\n    u = zero(len(a))\n    p = a.pivotize()\n    a = p.mul(a)\n    for j := range a {\n        l[j][j] = 1\n        for i := 0; i <= j; i++ {\n            sum := 0.\n            for k := 0; k < i; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            u[i][j] = a[i][j] - sum\n        }\n        for i := j; i < len(a); i++ {\n            sum := 0.\n            for k := 0; k < j; k++ {\n                sum += u[k][j] * l[i][k]\n            }\n            l[i][j] = (a[i][j] - sum) / u[j][j]\n        }\n    }\n    return\n}\n\nfunc main() {\n    showLU(matrix{\n        {1, 3, 5},\n        {2, 4, 7},\n        {1, 1, 0}})\n    showLU(matrix{\n        {11, 9, 24, 2},\n        {1, 5, 2, 6},\n        {3, 17, 18, 1},\n        {2, 5, 7, 1}})\n}\n\nfunc showLU(a matrix) {\n    a.print(\"\\na\")\n    l, u, p := a.lu()\n    l.print(\"l\")\n    u.print(\"u\") \n    p.print(\"p\") \n}\n", "C": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define foreach(a, b, c) for (int a = b; a < c; a++)\n#define for_i foreach(i, 0, n)\n#define for_j foreach(j, 0, n)\n#define for_k foreach(k, 0, n)\n#define for_ij for_i for_j\n#define for_ijk for_ij for_k\n#define _dim int n\n#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }\n#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }\n\ntypedef double **mat;\n\n#define _zero(a) mat_zero(a, n)\nvoid mat_zero(mat x, int n) { for_ij x[i][j] = 0; }\n\n#define _new(a) a = mat_new(n)\nmat mat_new(_dim)\n{\n\tmat x = malloc(sizeof(double*) * n);\n\tx[0]  = malloc(sizeof(double) * n * n);\n\n\tfor_i x[i] = x[0] + n * i;\n\t_zero(x);\n\n\treturn x;\n}\n\n#define _copy(a) mat_copy(a, n)\nmat mat_copy(void *s, _dim)\n{\n\tmat x = mat_new(n);\n\tfor_ij x[i][j] = ((double (*)[n])s)[i][j];\n\treturn x;\n}\n\n#define _del(x) mat_del(x)\nvoid mat_del(mat x) { free(x[0]); free(x); }\n\n#define _QUOT(x) #x\n#define QUOTE(x) _QUOT(x)\n#define _show(a) printf(QUOTE(a)\" =\");mat_show(a, 0, n)\nvoid mat_show(mat x, char *fmt, _dim)\n{\n\tif (!fmt) fmt = \"%8.4g\";\n\tfor_i {\n\t\tprintf(i ? \"      \" : \" [ \");\n\t\tfor_j {\n\t\t\tprintf(fmt, x[i][j]);\n\t\t\tprintf(j < n - 1 ? \"  \" : i == n - 1 ? \" ]\\n\" : \"\\n\");\n\t\t}\n\t}\n}\n\n#define _mul(a, b) mat_mul(a, b, n)\nmat mat_mul(mat a, mat b, _dim)\n{\n\tmat c = _new(c);\n\tfor_ijk c[i][j] += a[i][k] * b[k][j];\n\treturn c;\n}\n\n#define _pivot(a, b) mat_pivot(a, b, n)\nvoid mat_pivot(mat a, mat p, _dim)\n{\n\tfor_ij { p[i][j] = (i == j); }\n\tfor_i  {\n\t\tint max_j = i;\n\t\tforeach(j, i, n)\n\t\t\tif (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;\n\n\t\tif (max_j != i)\n\t\t\tfor_k { _swap(p[i][k], p[max_j][k]); }\n\t}\n}\n\n#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)\nvoid mat_LU(mat A, mat L, mat U, mat P, _dim)\n{\n\t_zero(L); _zero(U);\n\t_pivot(A, P);\n\n\tmat Aprime = _mul(P, A);\n\n\tfor_i  { L[i][i] = 1; }\n\tfor_ij {\n\t\tdouble s;\n\t\tif (j <= i) {\n\t\t\t_sum_k(0, j, L[j][k] * U[k][i], s)\n\t\t\tU[j][i] = Aprime[j][i] - s;\n\t\t}\n\t\tif (j >= i) {\n\t\t\t_sum_k(0, i, L[j][k] * U[k][i], s);\n\t\t\tL[j][i] = (Aprime[j][i] - s) / U[i][i];\n\t\t}\n\t}\n\n\t_del(Aprime);\n}\n\ndouble A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};\ndouble A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};\n\nint main()\n{\n\tint n = 3;\n\tmat A, L, P, U;\n\n\t_new(L); _new(P); _new(U);\n\tA = _copy(A3);\n\t_LU(A, L, U, P);\n\t_show(A); _show(L); _show(U); _show(P);\n\t_del(A);  _del(L);  _del(U);  _del(P);\n\n\tprintf(\"\\n\");\n\n\tn = 4;\n\n\t_new(L); _new(P); _new(U);\n\tA = _copy(A4);\n\t_LU(A, L, U, P);\n\t_show(A); _show(L); _show(U); _show(P);\n\t_del(A);  _del(L);  _del(U);  _del(P);\n\n\treturn 0;\n}\n"}
